2012-06-23 104 views
2

當我連接到我的只讀數據庫(現在在jar中)時,我可以運行應用程序,但是當我嘗試運行查詢時,它凍結了應用程序。我不知道我做錯了,我也跟着this guide只讀Derby數據庫凍結

這是我如何連接到數據庫

try 
{ 
    Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance(); 
    connection = DriverManager.getConnection("jdbc:derby:jar:(database.jar)MyDbTest;"); 
    statement = connection.createStatement(); 
} 
catch (Exception e) 
{ 
    e.printStackTrace(); 
} 
+2

您是否已將「derby.storage.tempDirectory」和「derby.stream.error.file」屬性設置爲可寫入的臨時目錄? – Sascha

+0

@Sascha可能是它..我如何將目錄設置在jar文件的外部?我希望這可以在Windows和Mac上工作,所以我不想把它放在C://或/ usr之類的地方或類似的地方。 – Mukhi

回答

2

因此,這裏是我的簡單的設置,在這裏我設置必要的臨時目錄屬性。

private static void accessReadOnlyJar() { 
    try { 
     Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance(); 
     Properties props = new Properties(); 
     String tempDir = System.getProperty("java.io.tmpdir"); 
     props.setProperty("derby.storage.tempDirectory", tempDir); 
     props.setProperty("derby.stream.error.file", tempDir+"derby_error.log"); 
     Connection connection = DriverManager.getConnection("jdbc:derby:jar:(data/db.jar)derbyDB", props); 

     Statement statement = connection.createStatement(); 
     ResultSet result = statement.executeQuery("SELECT * FROM TESTTABLE"); 
     while(result.next()){ 
      System.out.println(result.getString("NAME")); 
     } 

     connection.close(); 
    } catch (InstantiationException e) { 
     e.printStackTrace(); 
    } catch (IllegalAccessException e) { 
     e.printStackTrace(); 
    } catch (ClassNotFoundException e) { 
     e.printStackTrace(); 
    } catch (SQLException e) { 
     e.printStackTrace(); 
    } 
} 

您的tempDir良好的位置可能是:

  • 的系統臨時目錄:System.getProperty("java.io.tmpdir")
  • 你的工作目錄:"."
  • 您的應用程序目錄:ClassLoader.getSystemClassLoader().getResource(".").getPath()

或任何相對於它;-)

如果這不能解決您的問題,請檢查/重新創建您的數據庫。如果在打包jar之前它沒有關閉 ,德比將始終在啓動時嘗試恢復。

+0

我想我的數據庫沒有正常關閉,但我完全按照指南中的說法進行操作,並使用與終端命令相同的選項。有任何想法嗎? – Mukhi

+1

關閉你的數據庫,提交所有事務並調用'DriverManager.getConnection(「jdbc:derby:MyDbTest; shutdown = true」);'see:[DerbyTut](http://db.apache.org/derby/papers/ DerbyTut/embedded_intro.html#關機) – Sascha