首页 新闻 赞助 找找看

JDBC运行问题

0
[已解决问题] 解决于 2017-12-25 16:22

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

}

}

哪位大牛知道这段代码为什么会卡住?

it_hacker的主页 it_hacker | 菜鸟二级 | 园豆:202
提问于:2017-12-25 14:12
< >
分享
最佳答案
0

你为什么把那commit给注释掉了?你注释掉了锁还不会释放第二句没办法完成执行的

奖励园豆:5
Daniel Cai | 专家六级 |园豆:10424 | 2017-12-25 14:50

我尝试了不同的提交位置,下面有提交的

 

it_hacker | 园豆:202 (菜鸟二级) | 2017-12-25 14:52

@it_hacker: 放下面没用,你两个连接对象

conn1->拿取数据锁->更新

conn2->拿取数据锁

后面才是conn1的提交,最后释放对应数据的锁。

Daniel Cai | 园豆:10424 (专家六级) | 2017-12-25 15:10
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册