如何在Derby中创建缺少的数据库视图?

时间:2016-03-06 20:24:06

标签: java jdbc derby sql-view database-metadata

我想在我的WebApp启动时在Derby RDBMS中创建一个视图(ApplicationListener.contextInitialized),如果它还不存在的话。在这个时间点没有交易所以我必须使用JDBC& SQL。 我对DatabaseMetaData.getTables()的尝试不成功。它总是返回一个空的结果集,但是我可以在NetBeans的“服务”选项卡中看到它确定存在(以及所请求的表)。代码:

public isDBViewExists( Connection conn_, String catalogName_, String schemaName_, String viewName_ ) throws SQLException
{
  conn_.setAutoCommit( false );
  DatabaseMetaData metadata = conn_.getMetaData();
  ResultSet rs = metadata.getTables( catalogName_, schemaName_, viewName_, new String[] { "VIEW" } );
  return rs.next();
}

由应用程序上下文事件处理程序中注入的DataSource资源创建的Connection:

@Resource( name="jdbc/x" )
DataSource ds;
...
try
{
  Connection conn = ds.getConnection();
  if ( isDBViewExists( conn, ... ) )
  ...
}
finally
{
  conn.close();
}

所有传递的名称都在upperCase(catalog,schema,view / table)中。 conn_不为null。我的错是什么?

1 个答案:

答案 0 :(得分:1)

在这种情况下,如果表已经存在,那么创建表并忽略返回的SQLException可能更容易。让DB担心检查表是否已存在。

例如:

Connection conn = ds.getConnection()
try {
  conn.createStatement().executeUpdate("CREATE TABLE ....");
} finally {
  conn.close();
} catch(SQLException ignore) {
  // ignore exception, not much can go wrong here except for the table already existing.

  // If you don't mind making vendor specific logic, check the error message for "already exists" or some equivalent
  if(!ignore.getMessage().contains("already exists"))
    throw ignore;
}