6

We created a java application which uses the JavaDB database in Netbeans IDE. We want the program to check every time it starts if the database's tables have already been created, and otherwise create them. How do we do that? thanx

smash
  • 61
  • 1
  • 2
  • possible duplicate of [How to check if a database exists in Hsqldb/Derby?](http://stackoverflow.com/questions/3801773/how-to-check-if-a-database-exists-in-hsqldb-derby) – Raedwald Sep 02 '13 at 16:15
  • garlicman's answer is correct, only i add that the search of the table must be in upper case because despite you have created your table in lowercase, the metadata is in uppercase – Marco Van Jul 10 '17 at 19:35

2 Answers2

6

I use :

DatabaseMetaData metas;
ResultSet tables;
Statement stat;

m_connexion = DriverManager.getConnection("jdbc:derby:mybase;create=true");
metas = m_connexion.getMetaData();
stat = m_connexion.createStatement();
tables = metas.getTables(m_connexion.getCatalog(), null, "MYTABLE", null);
if (!tables.next())
  stat.execute(
    "CREATE TABLE APP.MYTABLE (" // etc.

... and it's work for me.

Istao
  • 7,425
  • 6
  • 32
  • 39
0

Istao's test for the existence of a table didn't work for me with Derby. The table was never found even though it was previously created. What what missing is you have to specify the TABLE_SCHEM as "APP", then set the table type to include "TABLE". Maybe using null worked in previous versions, but using Derby 10.12 doesn't find a previously created table with these parameters set to null.

Connection conn = DriverManager.getConnection(DB_PROTO + DB_NAME + ";create=true");
DatabaseMetaData metas = conn.getMetaData();
ResultSet tables = metas.getTables(conn.getCatalog(), "APP", TABLE_NODES, new String[] {"TABLE"});
if (!tables.next()) {
    Statement stat = conn.createStatement();
    stat.execute("create table " + ...

Hope this helps someone else.

dubmojo
  • 6,660
  • 8
  • 41
  • 68