java - 调用executeUpdate()后超时

标签 java jdbc timeout connection-timeout

我在 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/

相关文章:

java - 在java中读取二进制文件时将小端转换为大端

java - 类型不匹配 : cannot convert from element type Object to String JDBC MetaData

java - 使用 mysql-connector-java jdbc 驱动程序 8.0.18 为 MySQL 8 服务器获取时间戳列的错误值

java - Guava 缓存/可配置驱逐/缓冲区替换策略

java - Assets 中的图像看不到

Java 6 NTLM 代理身份验证和 HTTPS - 有人让它工作吗?

java - rs.getGeneratedKeys() 在 Derby 中不起作用

android - https 连接适用于 Wifi (wlan) 但不适用于 3G/GPRS (umts)

timeout - ApiAxle:如果后端服务器响应缓慢,请修改超时参数

php - 为什么 curl 会忽略 CURLOPT_TIMEOUT_MS(但尊重 CURLOPT_TIMEOUT)?