How can I detect a SQL table's existence in Java?

You can use DatabaseMetaData.getTables() to get information about existing tables.

This method works transparently and is independent of the database engine. I think it queries information schema tables behind the scenes.

Edit:

Here is an example that prints all existing table names.

DatabaseMetaData md = connection.getMetaData();
ResultSet rs = md.getTables(null, null, "%", null);
while (rs.next()) {
  System.out.println(rs.getString(3));
}

Use java.sql.DatabaseMetaData.getTables(null, null, YOUR_TABLE, null). If the table exists, you will get a ResultSet with one record.

See DatabaseMetaData.getTables


For ALL ANSI-compliant databases: (mySQL, SQL Server 2005/2008, Oracle, PostgreSQL, SQLLite, maybe others)

select 1 from information_schema.tables where table_name = @tableName

Tags:

Database

Sql

Java