您需要连接的地方应该得到连接。
确保没有资源“泄漏”的方法是使用 java 7 的 try-with-resource 语法:
public String fetchSomeData() {
try (Connection conn = getConnection()) { // This line, with this syntax, will ensure that it is automatically closed in an invisible "finally" block
// Do what you need to do with the data, return it or something else
} catch (SQLException e) {
// No need to do clean up here, log the exception or do whatever you want.
}
}
您可以在任何实现 AutoCloseable 接口的对象上使用 try-with-resource 语法。这包括 Connection、Statement 和 Resultset 等。
如果您需要执行事务,您可能希望在方法中初始化 Connection,然后将该 Connection 传递给添加到事务中的其他不同方法,然后提交它。如果是这种情况,您可以这样做:
public String fetchSomeDataInTransactionStyle() {
try (Connection conn = getConnection()) { // This line, with this syntax, will ensure that it is automatically closed in an invisible "finally" block
conn.setAutocommit(false);
addSomethingToTransaction(conn);
addSomethingMore(conn);
conn.commit();
} catch (SQLException e) {
// No need to do clean up here, log the exception or do whatever you want.
}
}