2016-09-18 71 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

相关问题