【问题标题】:How to create missing database view in Derby?如何在 Derby 中创建缺失的数据库视图?
【发布时间】:2016-06-20 07:34:42
【问题描述】:

如果我的 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资源创建的Connection:

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

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

【问题讨论】:

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


    【解决方案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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-20
      • 1970-01-01
      • 1970-01-01
      • 2014-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多