Bal*_*usC 10
永远.您需要在尽可能短的范围内获取和关闭它们,以避免资源泄漏,事务性问题和耗尽的连接池.不这样做会导致数据库迟早耗尽资源,导致"太多连接"等异常.
正常的JDBC习惯用法如下,所有资源都在同一个try-with-resources块中打开和关闭:
public List<Entity> list() throws SQLException {
List<Entity> entities = new ArrayList<Entity>();
try (
Connection connection = database.getConnection();
PreparedStatement statement = connection.prepareStatement(SQL_LIST);
ResultSet resultSet = statement.executeQuery();
) {
while (resultSet.next()) {
entities.add(map(resultSet));
}
}
return entities;
}
Run Code Online (Sandbox Code Playgroud)
或者当你还没有使用Java 7时:
public List<Entity> list() throws SQLException {
List<Entity> entities = new ArrayList<Entity>();
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
connection = database.getConnection();
statement = connection.prepareStatement(SQL_LIST);
resultSet = statement.executeQuery();
while (resultSet.next()) {
entities.add(map(resultSet));
}
} finally {
if (resultSet != null) try { resultSet.close(); } catch (SQLException logOrIgnore) {}
if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {}
if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
}
return entities;
}
Run Code Online (Sandbox Code Playgroud)
使用PreparedStatement将为您提供数据库缓存语句的好处(正确使用时,SQL注入防护旁边).获取和关闭连接是最昂贵的任务,但是发明了连接池.如果要重用相同的语句来执行批量插入/更新,则可以使用批处理.
| 归档时间: |
|
| 查看次数: |
3914 次 |
| 最近记录: |