您永远不要
ResultSet通过公共方法来回避。这很容易导致资源泄漏,因为您不得不保持语句和连接打开。关闭它们将隐式关闭结果集。但是,将它们保持打开状态将导致它们悬而未决,并且当它们打开过多时,将导致数据库用尽资源。
像这样将其映射到Javabeans的集合,并返回它:
public List<Biler> list() throws SQLException { Connection connection = null; PreparedStatement statement = null; ResultSet resultSet = null; List<Biler> bilers = new ArrayList<Biler>(); try { connection = database.getConnection(); statement = connection.prepareStatement("SELECt id, name, value FROM Biler"); resultSet = statement.executeQuery(); while (resultSet.next()) { Biler biler = new Biler(); biler.setId(resultSet.getLong("id")); biler.setName(resultSet.getString("name")); biler.setValue(resultSet.getInt("value")); bilers.add(biler); } } finally { if (resultSet != null) try { resultSet.close(); } catch (SQLException ignore) {} if (statement != null) try { statement.close(); } catch (SQLException ignore) {} if (connection != null) try { connection.close(); } catch (SQLException ignore) {} } return bilers;}或者,如果您已经在使用Java 7,则只需使用try-with-
resources语句即可自动关闭这些资源:
public List<Biler> list() throws SQLException { List<Biler> bilers = new ArrayList<Biler>(); try ( Connection connection = database.getConnection(); PreparedStatement statement = connection.prepareStatement("SELECt id, name, value FROM Biler"); ResultSet resultSet = statement.executeQuery(); ) { while (resultSet.next()) { Biler biler = new Biler(); biler.setId(resultSet.getLong("id")); biler.setName(resultSet.getString("name")); biler.setValue(resultSet.getInt("value")); bilers.add(biler); } } return bilers;}顺便说一句,你不应该声明
Connection,
Statement并
ResultSet在所有的实例变量(主要threadsafety问题!),也被吞噬
SQLException所有在这一点上(主叫方将不知道发生了问题),也被关闭资源相同
try(例如,如果结果集close抛出异常,则语句和连接仍处于打开状态)。所有这些问题已在上述代码段中修复。



