该Statement.setQueryTimeout()方法以秒为单位设置查询执行时间的限制。当该值设置为零时,表示执行没有超时限制。
package org.nhooo.example.jdbc; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.sql.SQLException; import java.sql.DriverManager; public class QueryTimeout { private static final String URL = "jdbc:mysql://localhost/nhooo"; private static final String USERNAME = "root"; private static final String PASSWORD = ""; public static void main(String[] args) { try (Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD)) { Statement stmt = connection.createStatement(); // 设置驾驶员等待的秒数 // 一个执行给定数量的语句对象 //秒。如果超出限制,则抛出SQLException // 被抛出。 stmt.setQueryTimeout(60); // 执行SQL查询 ResultSet rs = stmt.executeQuery("select * from products"); while (rs.next()) { System.out.println("code: " + rs.getString("code") + " ,product: " + rs.getString("name") + " ,price: " + rs.getDouble("price")); } } catch (SQLException e) { e.printStackTrace(); } } }
Maven依赖
<!-- https://search.maven.org/remotecontent?filepath=mysql/mysql-connector-java/8.0.17/mysql-connector-java-8.0.17.jar --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.17</version> </dependency>