Java SQL Table Column columnExists(Connection con, String tableName, String columnName)

Here you can find the source of columnExists(Connection con, String tableName, String columnName)

Description

Tests if a column exists in the database

License

GNU General Public License

Parameter

Parameter Description
con a connection to a database
tableName the name of a table containing the column
columnName the name of the column to test for

Exception

Parameter Description
SQLException if an error occurs in the underlying database
NullPointerException if tableName is null

Return

true if the column exists, false otherwise

Declaration

public static boolean columnExists(Connection con, String tableName, String columnName) throws SQLException 

Method Source Code


//package com.java2s;
/*//  w  w  w. j a  v a 2  s  .co  m
 * Copyright (C) 2002-2014 FlyMine
 *
 * This code may be freely distributed and modified under the
 * terms of the GNU Lesser General Public Licence.  This should
 * be distributed with the code.  See the LICENSE file for more
 * information or http://www.gnu.org/copyleft/lesser.html.
 *
 */

import java.sql.Connection;

import java.sql.ResultSet;
import java.sql.SQLException;

public class Main {
    /**
     * Tests if a column exists in the database
     *
     * @param con a connection to a database
     * @param tableName the name of a table containing the column
     * @param columnName the name of the column to test for
     * @return true if the column exists, false otherwise
     * @throws SQLException if an error occurs in the underlying database
     * @throws NullPointerException if tableName is null
     */
    public static boolean columnExists(Connection con, String tableName, String columnName) throws SQLException {
        if (tableName == null) {
            throw new NullPointerException("tableName cannot be null");
        }
        if (columnName == null) {
            throw new NullPointerException("columnName cannot be null");
        }

        ResultSet res = con.getMetaData().getColumns(null, null, tableName, columnName);

        while (res.next()) {
            if (res.getString(3).equals(tableName) && res.getString(4).equals(columnName)) {
                return true;
            }
        }
        return false;
    }
}

Related

  1. columnExists(Connection connection, String table, String column)
  2. columnLabels(final ResultSet results)
  3. containsColumn(ResultSet rs, String columnName)
  4. extractColumnTypeName(ResultSetMetaData resultSetMetaData, int index)