简体   繁体   English

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

[英]How to create missing database view in Derby?

I'd like to create a view in Derby RDBMS when my WebApp starts up (ApplicationListener.contextInitialized) if it does not exist yet. 如果我的WebApp启动(ApplicationListener.contextInitialized)尚不存在,我想在Derby RDBMS中创建一个视图。 In this point of time there is not a transaction so I have to use JDBC & SQL. 在这一时间点上没有事务,因此我必须使用JDBC&SQL。 My tries with DatabaseMetaData.getTables() were not successfull. 我对DatabaseMetaData.getTables()的尝试未成功。 It gives back always an empty result set but I can see in the Services tab in NetBeans it definitively exists (and the requested table as well). 它总是返回空结果集,但我可以在NetBeans的“服务”选项卡中看到它明确存在(以及请求的表)。 The code: 编码:

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

The Connection created by the injected DataSource resource in the app context event handler: 由应用上下文事件处理程序中注入的DataSource资源创建的Connection:

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

All of the passed names are in upperCase (catalog, schema, view/table). 所有传递的名称都在upperCase中(目录,架构,视图/表)。 The conn_ is not null. conn_不为null。 What is my fault? 我怎么了

In this case it's probably easier to just create the table and ignore the SQLException that comes back if the table already exists. 在这种情况下,创建表并忽略表已经存在时返回的SQLException可能会更容易。 Let the DB worry about checking if the table exists already. 让DB担心检查表是否已经存在。

For example: 例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM