Sun*_*pta 7 java mysql transactions jdbc
我有一个名为MySQL表Student有两列Student_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)
Run Code Online (Sandbox Code Playgroud)
以下是产生错误的代码:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
我试图使用connection1我使用另一个connection对象插入的对象删除行.
为什么我收到此错误?
修改您的代码并按如下方式重新排序执行.它应该工作正常:
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();
Run Code Online (Sandbox Code Playgroud)
问题是,当您尝试执行新的删除语句在DB中创建死锁情况时,先前执行的insert语句尚未提交并在表上保持锁定.
| 归档时间: |
|
| 查看次数: |
15520 次 |
| 最近记录: |