原文地址:https://www.codelooru.com/2017/02/how-to-timeout-jdbc-queries.html
怎样为JDBC查询设置超时
JDBC查询默认情况下是没有超时的,这就意味着如果一个查询被阻塞,那么这个线程将会被一直阻塞。当这些查询花费的时间超过一定时间段,那么以timeout方式终止则是一种最佳实践。
单个查询的超时设置
JDBC的statement可以设置超时,单位为秒。当超时被设置,驱动将会等待设置的时间。如果在设置的时间内没有返回,怎会抛出SQLTimeoutException异常。
下面是两个例子:
Statement stmt = connection.prepareStatement("SELECT * FROM BOOKS");
stmt.setQueryTimeout(10);//Timeout of 10 seconds
//This would throw an SQLTimeoutException if it exceeds 10 seconds
ResultSet result = stmt.executeQuery();
PreparedStatement stmt = connection.prepareStatement("UPDATE BOOKS SET RETURNED = ? WHERE BID = ?");
stmt.setBoolean(1, true);
stmt.setString(2, "B1234");
stmt.setQueryTimeout(5);//Timeout of 5 seconds
//This would throw an SQLTimeoutException if it exceeds 5 seconds
stmt.executeUpdate();
全局超时设置(JDBC驱动级别)
如果需要为所有的查询都设置相同的超时,可以直接在驱动上设置。
然而,不同的驱动会有不同的设置方式。
下面是Oracle Thin Driver的设置实例:
Properties properties = new Properties();
properties.setProperty("user", "scott");
properties.setProperty("password", "tiger");
//This timeout is in milliseconds, but can vary for other drivers
properties.setProperty(OracleConnection.CONNECTION_PROPERTY_THIN_READ_TIMEOUT, "2000");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@host:1521:SID", properties);
Spring JDBC 超时设置
如果使用Spring JDBC,用户不需要直接控制JDBC的statement。JDBCTemplate也提供了setQueryTimeOut的接口。如果设置成:-1,将会采用JDBC默认的超时设置。
getJdbcTemplate().setQueryTimeout(5);
getJdbcTemplate().update("UPDATE BOOKS ...", sqlParamSource);