Tells whether the table has the column with the given column Name, or not. - Java java.sql

Java examples for java.sql:Table

Description

Tells whether the table has the column with the given column Name, or not.

Demo Code

/*/*ww  w .ja  va2  s  .  co m*/
 * Zed Attack Proxy (ZAP) and its related class files.
 * 
 * ZAP is an HTTP/HTTPS proxy for assessing web application security.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0 
 *   
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License. 
 */
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.log4j.Logger;

public class Main{
    private static final Logger logger = Logger.getLogger(DbUtils.class);
    /**
     * Tells whether the table {@code tableName} has the column with the given
     * {@code columnName}, or not.
     * 
     * @param connection
     *            the connection to the database
     * @param tableName
     *            the name of the table that may have the column
     * @param columnName
     *            the name of the column that will be checked
     * @return {@code true} if the table {@code tableName} has the column
     *         {@code columnName}, {@code false} otherwise.
     * @throws SQLException
     *             if an error occurred while checking if the table has the
     *             column
     */
    public static boolean hasColumn(final Connection connection,
            final String tableName, final String columnName)
            throws SQLException {
        boolean hasColumn = false;

        ResultSet rs = null;
        try {
            rs = connection.getMetaData().getColumns(null, null, tableName,
                    columnName);
            if (rs.next()) {
                hasColumn = true;
            }
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
            } catch (SQLException e) {
                if (logger.isDebugEnabled()) {
                    logger.debug(e.getMessage(), e);
                }
            }
        }

        return hasColumn;
    }
}

Related Tutorials