问题
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
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/3437765/javadb-checking-if-a-database-exists