Java SQL Table columnExist(String table, String column, Connection con)

Here you can find the source of columnExist(String table, String column, Connection con)

Description

column Exist

License

Apache License

Declaration

public static boolean columnExist(String table, String column, Connection con) throws SQLException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import java.util.List;

public class Main {
    public static boolean columnExist(String table, String column, Connection con) throws SQLException {
        return getColumns(table, con).contains(column.toUpperCase());
    }/*from w ww. java  2 s  . c  om*/

    public static List<String> getColumns(String table, Connection con) throws SQLException {
        List<String> columns = new ArrayList<String>();

        // in some system, the table name is lower-case
        // in some system, the table name is upper case.
        // we find out the case first.
        DatabaseMetaData metaData = con.getMetaData();
        table = normalizeTableName(table, con);

        ResultSet rs = metaData.getColumns(null, null, table, null);
        try {
            while (rs.next()) {
                String column = rs.getString("COLUMN_NAME").toUpperCase();
                columns.add(column.toUpperCase());
            }
        } finally {
            rs.close();
        }
        return columns;

    }

    public static String normalizeTableName(String table, Connection con) throws SQLException {
        for (String t : getTables(con)) {
            if (t.equalsIgnoreCase(table)) {
                return t;
            }
        }
        return table;
    }

    public static List<String> getTables(Connection con) throws SQLException {
        String[] types = { "TABLE" };
        ResultSet rs = con.getMetaData().getTables(null, null, "%", types);
        List<String> tables = new ArrayList<String>();
        while (rs.next()) {
            tables.add(rs.getString("TABLE_NAME"));
        }
        rs.close();
        return tables;

    }
}

Related

  1. clearTables(Connection conn)
  2. clearTables(Connection conn, String[] tables)
  3. clearTables(Connection connection)
  4. constructObject(Class theClass, Connection db, int objectId, String tableName, String uniqueField)
  5. count(Connection conn, String table)
  6. countTables(Connection connection)
  7. createBagValuesTables(Connection con)