tags:

views:

154

answers:

3

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?

+6  A: 

You can use the available meta data:

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

See here for more details.

Brian Agnew
Thank you!!!!!!
Dmitry
A: 

Ok, and how to do the same thing with data base not a table?

Dmitry
...you get an exception trying to connect to the database?
Tomislav Nakic-Alfirevic
This is not an answer. This is a question. Use `Ask Question` button, not `Post Your Answer` button.
BalusC
Yes, for the first time I execute a program there is no any databases...
Dmitry
+1  A: 
DatabaseMetaData dbm = con.getMetaData();
// check if "employee" table is there
ResultSet tables = dbm.getTables(null, null, "employee", null);
if (rs.next()) {
  // Table exists
}
else {
  // Table does not exist
}
RealHowTo