使用JDBC向数据库中插入记录,有两种方式:
Nested try.. finally :在这种方法中,嵌套 try 和 finally 用于关闭 prepare 语句和连接
public void performInsert(String insertSQL) { try { Connection connection = dataSource.getConnection(); try { PreparedStatement insertStmt = connection .prepareStatement(insertSQL); try { // bind value to prepare statements insertStmt.executeUpdate(); } finally { insertStmt.close(); } } finally { connection.close(); } } catch (SQLException e) { // TODO: handle exception } }
public void performInsertIF(String insertSQL) {
Connection connection = null;
PreparedStatement insertStmt = null;
try {
connection = dataSource.getConnection();
insertStmt = connection.prepareStatement(insertSQL);
// bind value to prepare statements
insertStmt.executeUpdate();
}catch (SQLException e) {
// TODO: handle exception
} finally {
if( insertStmt != null) {
try {
insertStmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if( connection != null) {
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
上述两种方法都可以正常工作,但哪种方法更好用,为什么?
最佳答案
在上面的代码中,两种方法都可以正常工作,但第二种方法在某种程度上更好,因为您在调用 close()
之前检查了一个 null
对象。在空对象上调用 close()
将抛出 NullPointerException
。
但是,现在在 Java 7+ 中,您可以使用一个更好的替代方案,称为 try-with-resources .
关于java - 嵌套尝试 finally 或使用 if 条件尝试哪种方法更好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23931890/