我需要一个好方法来关闭 Java 中的 SQLite 连接。经过其他用户的一些建议后,我决定在代码中添加一个 finally
block ,以确保始终执行关闭操作。
public static boolean executeQuery(String query)
{
Connection conn = null;
Statement stmt = null;
try
{
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection(Global.dbPath);
stmt = conn.createStatement();
stmt.execute(query);
return true;
}
catch(ClassNotFoundException e)
{
System.out.println(e);
return false;
}
catch(SQLException e)
{
System.out.println(e);
return false;
}
finally
{
try
{
stmt.close();
conn.close();
return true;
}
catch (SQLException ex)
{
System.out.println ("Errore closing connections");
return false;
}
}
}
我不确定这是否是最佳解决方案。
如何优化它以提高可读性?
最佳答案
一些评论;简而言之:
- 将 SQL 异常与反射异常分开。
- 您的 SQL 异常可以恢复吗?如果没有,则抛出特定于应用程序的
RuntimeException
。 - 将连接和语句关闭异常封装在您的或第三方的实用方法中。
- 不要忽视异常处理;转储堆栈跟踪。
这会导致以下结果:
public static boolean executeQuery(String query) {
try {
Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException e) {
throw new DbException("Could not find JDBC driver", e);
}
Connection conn = null;
Statement stmt = null;
try {
conn = DriverManager.getConnection(Global.dbPath);
stmt = conn.createStatement();
stmt.execute(query);
return true;
} catch(SQLException e) {
throw new DbException("Exception during statement execution", e);
} finally {
DbUtils.closeQuietly(conn);
DbUtils.closeQuietly(stmt);
}
}
(我使用 Apache Commons 的 DbUtils 作为其 closeQuietly
,它会检查 null(您的没有)。您自己的版本可能会抛出特定于应用程序的异常,就像我在此处使用 DbException
所做的那样。这会将所有与数据库相关的异常包装到一个异常类中,该异常类可能是也可能不是您需要的。
关于java - 这是在 Java 中释放 SQLite 连接的最佳方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12297947/