0

如果我的 WebApp 启动 (ApplicationListener.contextInitialized) 尚不存在,我想在 Derby RDBMS 中创建一个视图。此时没有事务,所以我必须使用 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 资源创建的连接:

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

所有传递的名称都是大写的(目录、模式、视图/表)。conn_ 不为空。我的错是什么?

4

1 回答 1

1

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

例如:

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;
}
于 2016-03-06T21:23:40.300 回答