java.sql.SQLException: Query execution was interrupted

本文探讨了在使用MySQL-JDBC驱动连接MySQL数据库时遇到的长时间查询超时问题。通过设置短查询超时时间来尝试解决因服务器连接超时导致的问题,并讨论了如何正确配置和检测无效连接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

try {

int TIMEOUT = 5;
String url =
"jdbc:mysql://111.111.111.111/dbname?dontTrackOpenResources=true&useTimezone=true&serverTimezone=PST&zeroDateTimeBehavior=convertToNull&characterEncoding=utf-8&user=test&password=*****&connectTimeout=5000&socketTimeout=30000";

Statement st = null;
ResultSet rs = null;
try {
	if (con==null)
	{
		Class.forName("com.mysql.jdbc.Driver").newInstance();
		con = DriverManager.getConnection(url,"test", "****");
		DatabaseMetaData md = con.getMetaData();
		out.println("opened connection...");
		out.println(md.getDriverName()+" "+md.getDriverVersion());
		out.println(md.getDatabaseProductName()+" "+md.getDatabaseProductVersion());
	}
	st = con.createStatement();
	st.setQueryTimeout(TIMEOUT);
	rs = st.executeQuery("SELECT NOW()");
	rs.next();
	out.println(rs.getString(1));
} catch (Exception e) {
	out.println("mysql excepttion: "+e);
} finally {
	if (rs!=null)
		rs.close();
	if (st!=null)
		st.close();
}

} catch (Throwable e) {out.println("general exception: "+e);}

Set a short timeout on a long query.
This problem still exists in MySQL-AB JDBC Driver mysql-connector-java-5.1.6 connecting to
MySQL 5.0.27. The following code (JSP for convenience) will illustrate the problem after a
duration longer than the server's connection timeout.

After the timeout the query hangs indefinitely; instead I believe it should be possible
to detect that the connection is invalid by setting the Socket.setSoTimeout(int timeout)
parameter (e.g read-timeout) to be equal (or slightly larger) to the
Statement.getQueryTimeout()*1000 value. However Statement.setQueryTimeout(int secs) does
not result in the throwing of an SQLException (only an indefinate wait).

The server indeed appears not to have correctly closed the connection (netstat show
connected); however the driver should still be able to dtect the response timeout (for
the incorrect socket shutdown in addition to normal query timeouts)




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值