gpt4 book ai didi

java - 超过锁定等待超时;尝试使用 JDBC 重新启动事务

转载 作者:可可西里 更新时间:2023-11-01 06:37:33 26 4
gpt4 key购买 nike

我有一个名为 Student 的 MySQL 表,其中包含两列 Student_idname

我使用两个连接对象触发两个查询,它给了我一个异常:

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();
}
}

我正在尝试使用我使用其他 connection 对象插入的 connection1 对象删除行。

为什么会出现此错误?

最佳答案

修改您的代码并对执行重新排序,如下所示。它应该工作正常:

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();

问题是,当您尝试执行新的删除语句时,先前执行的插入语句尚未提交并持有表上的锁,从而在数据库中造成死锁情况。

关于java - 超过锁定等待超时;尝试使用 JDBC 重新启动事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18854988/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com