Java 超过锁定等待超时;尝试使用JDBC重新启动事务
我有一个名为Java 超过锁定等待超时;尝试使用JDBC重新启动事务,java,mysql,jdbc,transactions,Java,Mysql,Jdbc,Transactions,我有一个名为Student的MySQL表,有两列Student\u id和name 我正在使用两个连接对象触发两个查询,这给了我一个异常: Exception in thread "main" java.sql.SQLException: Lock wait timeout exceeded; try restarting transaction at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
Student
的MySQL表,有两列Student\u id
和name
我正在使用两个连接对象触发两个查询,这给了我一个异常:
Exception in thread "main" java.sql.SQLException: Lock wait timeout
exceeded; try restarting transaction
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4074)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4006)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2468)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2629)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2713)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2663)
at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:888)
at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:730)
at jdbc.ConnectUsingJdbc.main(ConnectUsingJdbc.java:19)
以下是产生错误的代码:
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class ConnectUsingJdbc {
public static void main(String[] args)
throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test","root","root");
Connection connection1 = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test","root","root");
connection.setAutoCommit(false);
connection1.setAutoCommit(false);
Statement statement = connection.createStatement();
statement.execute("insert into student values (3,'kamal')");
Statement statement1 = connection1.createStatement();
statement1.execute("delete from student where student_id = 3");
connection.commit();
connection1.commit();
}
}
我正在尝试使用我使用另一个连接插入的连接1
对象删除该行
为什么会出现此错误?修改代码并按如下顺序重新排列执行。它应该可以很好地工作:
Statement statement = connection.createStatement();
statement.execute("insert into student values (3,'kamal')");
connection.commit();
Statement statement1 = connection1.createStatement();
statement1.execute("delete from student where student_id = 3");
connection1.commit();
问题是,以前执行的insert语句尚未提交,当您试图执行一个新的delete语句时,会在表上保持锁,从而在DB中造成死锁。但是如果我使用一个连接对象,并且使用该对象创建两个不同的语句对象。这样就不会出现僵局的情况。你知道为什么会这样吗
Statement Statement=connection.createStatement();语句。执行(“插入学生值(3,'kamal')”;语句statement1=connection.createStatement();语句1.执行(“从学生中删除,其中学生id=3”);commit()代码>当使用单连接(单会话)时,DBMS可以知道这两条语句来自同一个客户机线程/会话-因此它可以通过处理未提交的数据来优化和避免死锁。请阅读事务隔离的相关内容
。如果我执行此操作,使用两个不同的线程,每个线程具有不同的连接对象,一个线程调用insert,另一个线程调用delete,那么在这种情况下,将不会出现任何死锁。我说得对吗?