Skip to content
Advertisement

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

How can I detect if a certain table exists in a given SQL database in Java?

Advertisement

Answer

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));
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement