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

How to create missing database view in Derby?

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

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();
}

应用程序上下文事件处理程序中注入的数据源资源创建的连接:

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

所有传递的名称都是大写的(目录、架构、view/table)。 conn_ 不为空。我有什么错?

在这种情况下,如果 table 已经存在,则只创建 table 并忽略返回的 SQLException 可能更容易。让数据库担心检查 table 是否已经存在。

例如:

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;
}