java 发出请求后关闭SQLite连接的正确方法是什么?

x7rlezfr  于 2023-04-28  发布在  Java
关注(0)|答案(1)|浏览(201)

我正在开发一个与SQLite db集成的Java桌面应用程序,我遇到了一个异常,显示为[SQLITE_BUSY] The database file is locked (database is locked)。我读了一点,发现每次发出请求后,我都需要 * 释放 * 数据库文件的连接。什么是正确的做法呢?假设我有:

try{
Connection connection = DriverManager.getConnection(DB_URL);
PreparedStatement ps = connection.prepareStatement("Select * from users"); 
ResultSet rs = ps.executeQuery();
...
ps = connection.prepareStatement("Select * from employees");
rs = ps.executeQuery(); // raises SQLException mentioned above
...
}catch(SQLException ex){}
kqlmhetl

kqlmhetl1#

您捕获SQLException并通过以下方式对其进行响应:

  • 把问题的相关信息抛诸脑后。
  • 继续,安静。

总之,这是危险的。你说得太委婉了。
如果你不能处理一个异常(记录它,不处理它)-并且注意几乎所有的异常都不能处理,正确的做法是把它扔到前面。任何本质上涉及数据库的方法都应该声明为throws SQLException。如果方法的性质比这更一般,您应该捕获SQLException,但将其作为其他东西(例如。例如throw new RuntimeException("unhandled", e);--当你不知道该怎么做,也不想想太多的时候,这是catch block中最裸露的部分)。
除此之外,关闭事物的正确方法是使用try-with。看起来像这样:

try (
  Connection connection = DriverManager.getConnection(DB_URL);
  PreparedStatement ps = connection.prepareStatement("Select * from users"); 
  ResultSet rs = ps.executeQuery();
) {

  // loop through rs here
  // do not call close() - there is no need.
}
// resources have been closed here, no matter how we exit the block.
// even if the code inside the block throws, or `return;`s.

如果你按照上面的方法做,你就不会有那种“锁定”的事情发生。除非你从多个线程与数据库交互,并且每个线程都在获取锁,在这种情况下,这会变得更加复杂。

相关问题