2016-09-18 142 views
1

我有如下因素的DbConnection如何使用java檢查sqlite中是否存在與數據庫的連接?

public class DBConnection { 

    protected Statement statement; 
    protected Connection connection = null; 

    public DBConnection() { 
     try { 
      Class.forName("org.sqlite.JDBC"); 
     } catch (ClassNotFoundException e1) { 
      e1.printStackTrace(); 
     } 
     try { 

      connection = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\ion\\Desktop\\sample.db"); 
       statement = connection.createStatement(); 
       statement.setQueryTimeout(30); 

       statement.executeUpdate("CREATE TABLE IF NOT EXISTS person (id STRING PRIMARY KEY NOT NULL," 
         + "name STRING, email STRING UNIQUE, password STRING)"); 

       statement.executeUpdate("CREATE TABLE IF NOT EXISTS message (id STRING PRIMARY KEY NOT NULL," 
         + "text STRING, subject STRING, dateMessage Date, parrentMessageId String , personId String, " 
         + "categoryId String," 
         + " FOREIGN KEY(personId) REFERENCES person(id),FOREIGN KEY(categoryId) REFERENCES category(id))"); 

       statement.executeUpdate(
         "CREATE TABLE IF NOT EXISTS category (id STRING PRIMARY KEY NOT NULL," + "name STRING)"); 



     } catch (SQLException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

,但如果我在Servlet中使用這樣

String id = personService.getIdByEmail(email); 

     message.setPersonId(id); 
     messageService.persist(message); 

,我叫這就要求不同的存儲庫兩次不同的服務(personRep和messageRep都擴展這個的DbConnection類)它給我"database is locked"

如何檢查連接是否已經存在?請幫助我..謝謝!

回答

0

您正在使用兩臺設備同時呼叫兩個服務。所以,Server將創建兩個線程並服務於這兩個請求。這兩個頭將同時打開兩個連接。並使用此連接,線程將執行具有CREATE table命令的SQL語句。這是DDL表達式。因此,線程獲取數據庫鎖定,其他線程將遇到瓶頸並給出例如「數據庫已鎖定」的異常。

您可以使用同步,以便只允許一個線程執行代碼。其他有待完成。

更多詳細信息https://www.sqlite.org/cvstrac/wiki?p=DatabaseIsLocked

+0

類似的東西?同步(鎖1){ \t \t \t \t \t \t \t \t連接=的DriverManager.getConnection( 「JDBC:源碼:C:\\用戶\\離子\\桌面\\ sample.db」); \t \t \t \t statement = connection.createStatement(); \t \t \t \t statement.setQueryTimeout(30); – joesid

相關問題