java.sql.Statement接口中有cancel()方法;
/*** Cancels this Statement
object if both the DBMS and* driver support aborting an SQL statement.* This method can be used by one thread to cancel a statement that* is being executed by another thread.** @exception SQLException if a database access error occurs or* this method is called on a closed Statement
* @exception SQLFeatureNotSupportedException if the JDBC driver does not support* this method*/
void cancel() throws SQLException;
首先:当我们的Statement执行executeQuery(String sql)的时候,其实执行该逻辑的线程会被阻塞一段时间从而等待网络IO返回或者超时;
所以你看注释上说
This method can be used by one thread to cancel a statement that is being executed by another thread.
例如在com.mysql.jdbc.StatementImpl类中的cancel实现,是向数据库发送了Kill Query指令
/*** Cancels this Statement object if both the DBMS and driver support* aborting an SQL statement. This method can be used by one thread to* cancel a statement that is being executed by another thread.*/
public void cancel() throws SQLException {
if (!this.statementExecuting.get()) {
return;
}
if (!this.isClosed &&
this.connection != null &&
this.connection.versionMeetsMinimum(5, 0, 0)) {
Connection cancelConn = null;
java.sql.Statement cancelStmt = null;
try {
cancelConn = this.connection.duplicate();
cancelStmt = cancelConn.createStatement();