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.
}
Very simplistic:
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[])