Java SQL Table Exist tableExists(Connection con, String tableName)

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

Description

Tests if a table exists in the database

License

GNU General Public License

Parameter

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

Exception

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

Return

true if the table exists, false otherwise

Declaration

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

Method Source Code


//package com.java2s;
/*/*  www.  j av a  2s. c  o 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 table exists in the database
     *
     * @param con a connection to a database
     * @param tableName the name of a table to test for
     * @return true if the table exists, false otherwise
     * @throws SQLException if an error occurs in the underlying database
     * @throws NullPointerException if tableName is null
     */
    public static boolean tableExists(Connection con, String tableName) throws SQLException {
        if (tableName == null) {
            throw new NullPointerException("tableName cannot be null");
        }

        ResultSet res = con.getMetaData().getTables(null, null, null, new String[] { "TABLE" });

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

Related

  1. tableExist(Statement stmt, String tablename)
  2. tableExists(Connection con, String table)
  3. tableExists(Connection conn, String name)
  4. tableExists(Connection conn, String tableName)
  5. tableExists(java.sql.Connection conn, java.lang.String table)
  6. tableExists(Statement stmt, String name)