我有时会遇到以下异常:
com.ibm.db2.jcc.b.gm: [jcc][t4][2030][11211][3.50.152] A communication error occurred during operations on the connection's underlying socket, socket input stream, or socket output stream. Error location: Reply.fill(). Message: Connection reset. ERRORCODE=-4499, SQLSTATE=08001
问题是,代码成功执行了一段时间,然后突然出现这个异常。然而,当我再次运行代码时它运行得很好。
有人能告诉我哪里出了问题,并提供一些建议来解决这个问题。
最佳答案
这是未正确关闭/释放 JDBC 资源的标志。您需要在尽可能短的范围内并关闭所有JDBC资源,即您需要在try<的
block 与您获得它们的方法 block 完全相同。例如finally
block 中以相反的顺序关闭它们
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
connection = database.getConnection();
statement = connection.createStatement();
resultSet = statement.executeQuery(SQL);
// ...
} 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) {}
}
如果您不尽快正确关闭它们,数据库迟早会把它掌握在自己手中,您的应用程序迟早会崩溃,就像您自己遇到的那样。
要提高连接性能,请使用连接池——尽管如此,您仍然需要以与上述相同的方式获取和关闭它们!现在只是连接池实现,它在后台担心实际上是否关闭连接。
关于Java JDBC : Reply. 填充(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1405452/