Shubham Maheshwari
Shubham Maheshwari

Reputation: 114

check if table exists, using a connection object in java

I need to check if a table with a specific "tablename" exists in a database from my java program.

The database may be of different type, viz. MS SQL Server, Oracle, DB2. I have a connection object to the database. Is there a single method that can work for all the types of databases? I might have to extend the java program to support more db Types, thus a single approach for all DB types would be very much helpful.

The code that I am using. This appears to work correctly against a SQL Server database but does not find the table in Oracle or DB2

DatabaseMetaData meta = conn.getMetaData(); 
ResultSet res = meta.getTables(null, null, "TABLE_NAME", null); 
if(!res.next()){ 
  //table does not exist. 
} else{
   //table exists. 
}

Upvotes: 1

Views: 6921

Answers (3)

Justin Cave
Justin Cave

Reputation: 231651

You can use the DatabaseMetaData.getTables() procedure to search the database for tables with a particular pattern. If you search for an exact name, you'll either get an empty ResultSet or a ResultSet with a single row telling you that the table exists.

This works for me against an Oracle database whether the table is owned by the current user or a different user.

import java.sql.*;
import oracle.jdbc.*;
public class TableExists
{
 public static String exists(String tableName)
     throws SQLException
 {
    Connection       conn = new OracleDriver().defaultConnection();
    DatabaseMetaData meta = conn.getMetaData(); 
    ResultSet res = meta.getTables(null, null, tableName, null); 
    if(!res.next()){ 
      return "Nope";
    } else{
      return "Yup";
    }
 }
}

Upvotes: 3

Stijn Geukens
Stijn Geukens

Reputation: 15628

Very simplistic:

SELECT
    1
FROM
    TABLE
;

If it throws an exception the table does not exist (or something else is wrong). Otherwise:

http://docs.oracle.com/javase/6/docs/api/java/sql/DatabaseMetaData.html#getTables(java.lang.String, java.lang.String, java.lang.String, java.lang.String[])

Upvotes: 1

Aditya Jain
Aditya Jain

Reputation: 1095

You can try getTables() method of DatabaseMetaData.

Upvotes: 2

Related Questions