我在Java中有一个JDBC MySQL连接.我的程序适用于简单的查询执行.
如果我运行相同的程序超过10个小时并执行查询,那么我收到以下MySQL异常:
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException:
Connection.close() has already been called. Invalid operation in
this state.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(
Native Method)
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException:
No operations allowed after statement closed.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(
Native Method)
Run Code Online (Sandbox Code Playgroud)
我没有close()在任何地方使用过方法.我创建了数据库连接并永远打开它并始终执行查询.我没有明确提到连接超时的地方.我无法确定问题所在.
这是我用于数据库连接的代码:
String driver = PropertyReader.getDriver();
String url = dbURLPath;
Class.forName(driver);
connectToServerDB = DriverManager.getConnection(url);
connectToServerDB.setAutoCommit(false);
Run Code Online (Sandbox Code Playgroud)
是什么导致了这种例外
Sla*_*hev 23
MySQL在超时8小时后终止连接.您可以通过在MySQL中设置wait_timeout变量来修改超时.
然而,通常情况下,应用程序保持连接这么长时间并不是一个好主意.更好的方法是使用池化API(如Apache DBCP)设置连接池,并从池中检索连接,而不是直接通过驱动程序.如果连接池由于某种原因(包括超时)而死亡,它也会关注重建池连接.