Dmitry Dmitry - 2 months ago 13x
Java Question

Check if table exists

I have a desktop application with a database embedded in it. When I execute my program I need to check that specific table exists, or create it if not.

Given a Connection object named conn for my database, how could I check this?


You can use the available meta data:

  DatabaseMetaData meta = con.getMetaData();
  ResultSet res = meta.getTables(null, null, "My_Table_Name", 
     new String[] {"TABLE"});
  while ( {
        "   "+res.getString("TABLE_CAT") 
       + ", "+res.getString("TABLE_SCHEM")
       + ", "+res.getString("TABLE_NAME")
       + ", "+res.getString("TABLE_TYPE")
       + ", "+res.getString("REMARKS")); 

See here for more details. Note also the caveats in the JavaDoc.