gunrose
发贴: 100
积分: 20
|
于 2003-03-07 10:09
建议 失败的关闭和释放 JDBC 连接可能导致其它用户的连接经历长时间的等待。虽然超时的JDBC 连接会被 Server 退回而被回收 ,但必须等待这种情形发生。 使用完 JDBC 资源后关闭它们,还可以显式关闭 JDBC ResultSets等资源。如果没有显式关闭语句,则在完成了相关语句之后会释放 ResultsSets资源。
所以请确保您构建的代码在所有情况下,甚至在异常和错误条件下,都能关闭和释放 JDBC 资源。以下代码显示了 JDBC 资源的获得和使用都封装在“Try-Catch-Finally”结构中。其中,在 finally 子句中处理 JDBC 资源的关闭,使所有情况下关闭都将发生。 关闭 JDBC Connection 和 PreparedStatement 的正确方式 Connection connection = null; PreparedStatement statement = null; ResultSet resultSet = null; StringBuffer sqlBuffer=new StringBuffer(); //TODO //... try { connection = getConnectionFromDataSource(); statement = connection.prepareStatement(sqlBuffer.toString()); resultSet = statement.executeQuery(); //TODO //... } catch (Throwable t) { //TODO //... } finally { try { if (resultSet != null) { resultSet.close(); } resultSet = null;
if (statement != null) { statement.close(); } statement = null;
if (connection != null) { connection.close(); } connection=null; } catch (Exception e) { //TODO //... } }
gunrose edited on 2003-03-07 10:13
|