在Java中执行一个SQL语句涉及许多步骤:
在每个步骤中都可以抛出SQLException.如果我们要处理所有异常并正确释放所有资源,代码将看起来像这样,4个TRY级别堆叠在彼此的顶部.
try {
Connection connection = dataSource.getConnection();
try {
PreparedStatement statement = connection.prepareStatement("SELECT 1 FROM myTable");
try {
ResultSet result = statement.executeQuery();
try {
if (result.next()) {
Integer theOne = result.getInt(1);
}
}
finally {
result.close();
}
}
finally {
statement.close();
}
}
finally {
connection.close();
}
}
catch (SQLException e) {
// Handle exception
}
Run Code Online (Sandbox Code Playgroud)
您是否可以提出更好(更短)的方式来执行语句,同时仍然释放所有消耗的资源?
如果您使用的是Java 7,那么try with resources语句会缩短这一点,并使其更易于维护:
try (Connection conn = ds.getConnection(); PreparedStatement ps = conn.prepareStatement(queryString); ResultSet rs = ps.execute()) {
} catch (SQLException e) {
//Log the error somehow
}
Run Code Online (Sandbox Code Playgroud)
请注意,关闭连接将关闭所有关联的Statements和ResultSets.