我想在 Web 应用程序启动时在 Derby RDBMS 中创建一个 View (ApplicationListener.contextInitialized)(如果该 View 尚不存在)。此时没有事务,所以我必须使用 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();
}
应用上下文事件处理程序中注入(inject)的 DataSource 资源创建的连接:
@Resource( name="jdbc/x" )
DataSource ds;
...
try
{
Connection conn = ds.getConnection();
if ( isDBViewExists( conn, ... ) )
...
}
finally
{
conn.close();
}
所有传递的名称均为大写(目录、模式、 View /表)。 conn_ 不为空。我有什么错?
最佳答案
在这种情况下,创建表并忽略表已存在时返回的 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;
}
关于java - 如何在 Derby 中创建缺失的数据库 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35832093/