我在 Java 程序中有以下场景:
...
try
// 1
PreparedStatement pstmt1 = conn.getPreparedStatement("SQL QUERY");
pstmt1.setQueryTimeout(1);
pstm.executeUpdate();
System.out.println("1 executed");
// 2
PreparedStatement pstmt2 = conn.getPreparedStatement("SQL QUERY");
pstmt2.setQueryTimeout(1);
pstmt2.executeUpdate();
System.out.println("2 executed");
// 3
PreparedStatement pstmt3 = conn.getPreparedStatement("SQL QUERY");
pstmt3.setQueryTimeout(1);
pstmt3.executeUpdate();
System.out.println("3 executed");
catch(Exception e){
e.printStackTrace();
}
...
如果我“拔掉电缆”,并且在第一次执行 update() 调用后与数据库的连接就丢失了。我怎样才能告诉程序只等待1秒,如果没有响应就立即进入catch?
现在发生的事情是程序在该点之后卡住了(第一个executeUpdate(),在输出“1执行”处)。
方法 pstmt.setQueryTimeout(1) 似乎不起作用。
我已在服务器的连接池属性上将连接超时设置为 10 秒。
几分钟后(半小时),我收到以下错误(预期错误):
The Connection Manager received a fatal connection error from the Resource Adapter for resource jdbc/JNDI_BD1. The exception which was received is com.ibm.websphere.ce.cm.StaleConnectionException: [jcc][t4][2030][11211][3.58.82] A communication error occurred during operations on the connection's underlying socket, socket input stream, or socket output stream. Error location: Reply.fill(). Message: No route to host. ERRORCODE=-4499, SQLSTATE=08001:com.ibm.db2.jcc.am.io: [jcc][t4][2030][11211][3.58.82] A communication error occurred during operations on the connection's underlying socket, socket input stream, or socket output stream. Error location: Reply.fill(). Message: No route to host. ERRORCODE=-4499, SQLSTATE=08001:java.net.SocketException: No route to host
非常感谢任何帮助。
最佳答案
并非所有驱动程序都支持查询超时。但即使他们这样做了:查询超时并不是为了检测网络超时。大多数可能的选项(如查询超时)将由数据库服务器处理(即:驱动程序询问服务器:如果需要的时间超过 xxx,则中止查询),或者驱动程序和/或服务器根本不支持它。
套接字超时是一个低得多的级别超时,大多数驱动程序都会有一个连接属性设置(so_timeout、套接字超时等)。
关于java - 调用executeUpdate()后超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13352648/