簡體   English   中英

如何在Derby中創建丟失的數據庫視圖?

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

如果我的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();
}

所有傳遞的名稱都在upperCase中(目錄,架構,視圖/表)。 conn_不為null。 我怎么了

在這種情況下,創建表並忽略表已經存在時返回的SQLException可能會更容易。 讓DB擔心檢查表是否已經存在。

例如:

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