JDBC事务处理-四大原则
原子性
一致性
隔离性
持久性
第一步:实现转账操作
假设在账户中,盖伦有余额5000元,赵信有余额2000元,
盖伦要向赵信转账1000元。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
public
static
void
outMoney(Connection conn,String name,
int
account)
throws
SQLException{
String sql=
"update t_account set balance=balance-? where name=?"
;
PreparedStatement pst=conn.prepareStatement(sql);
pst.setInt(
1
, account);
pst.setString(
2
, name);
int
result=pst.executeUpdate();
pst.close();
}
public
static
void
inMoney(Connection conn,String name,
int
account)
throws
SQLException{
String sql=
"update t_account set balance=balance+? where name=?"
;
PreparedStatement pst=conn.prepareStatement(sql);
pst.setInt(
1
, account);
pst.setString(
2
, name);
int
result=pst.executeUpdate();
pst.close();
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
System.out.println(
"盖伦正在给赵信转账1000元"
);
//转账操作
try
{
outMoney(conn,
"盖伦"
,
1000
);
inMoney(conn,
"赵信"
,
1000
);
}
catch
(SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try
{
System.out.println(
"转账成功!"
);
conn.close();
}
catch
(SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
|
运行:
正常转账成功。
假设 public static void inMoney(Connection conn,String name,int account)运行时出现意外。
人为构造意外
然后运行程序
查看数据库的数据
盖伦少了1000元,赵信余额没有变!
这样,赵信就坑了!!!
【改进】
所需要的函数
con.setAutoCommit(false); // 取消自动提交
con.rollback(); // 回滚
con.commit(); // 提交事务
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
Connection conn=
null
;
try
{
conn = dbUtil.getConnection();
System.out.println(
"盖伦正在给赵信转账1000元"
);
conn.setAutoCommit(
false
);
//取消自动提交
outMoney(conn,
"盖伦"
,
1000
);
inMoney(conn,
"赵信"
,
1000
);
}
catch
(ClassNotFoundException e) {
e.printStackTrace();
}
catch
(SQLException e) {
try
{
conn.rollback();
//回滚
}
catch
(SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
finally
{
try
{
conn.commit();
//提交
conn.close();
}
catch
(SQLException e) {
e.printStackTrace();
}
}
|