public class JDBCtest {
public static void main(String[] args) {
Connection connection1=null;
Connection connection2=null;
PreparedStatement prepareStatement=null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection1 = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/demo","root","zr129114");
connection2 = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/demo","root","zr129114");
connection2.setAutoCommit(false);
connection1.setAutoCommit(false);
prepareStatement = connection1.prepareStatement("update lala set result=result-1000 where id=1");
prepareStatement.executeUpdate();
// connection1.commit();
prepareStatement = connection2.prepareStatement("update lala set result=result-1000 where id=1");
prepareStatement.executeUpdate();
connection1.commit();
if(1>0) {
throw new SQLException();
}
prepareStatement = connection2.prepareStatement("update lala set result=result+1000 where id=2");
prepareStatement.executeUpdate();
connection2.commit();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
// try {
// connection2.rollback();
// } catch (SQLException e1) {
// e1.printStackTrace();
// }
}
finally {
if(null!=connection1)
try {
connection1.close();
} catch (SQLException e) {
e.printStackTrace();
}
if(null!=connection2)
try {
connection2.close();
} catch (SQLException e) {
e.printStackTrace();
}
if(null!=prepareStatement)
try {
prepareStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
哪位大牛知道这段代码为什么会卡住?
你为什么把那commit给注释掉了?你注释掉了锁还不会释放第二句没办法完成执行的
我尝试了不同的提交位置,下面有提交的
@it_hacker: 放下面没用,你两个连接对象
conn1->拿取数据锁->更新
conn2->拿取数据锁
后面才是conn1的提交,最后释放对应数据的锁。