JavaWeb学习笔记6——事务实例:转账(1)

转账记录表 账号 余额 最后修改日期

<%

while(rs.next())

{

String account=rs.getString(“account”);//获取账户名

double currency=rs.getDouble(“currency”);//获取账户余额

String last_modifield=rs.getTimestamp(“last_modified”).toString();//获取上次操作时间

out.println(“”);

out.println(“”+account+“”);//将账户名显示在表中

out.println(“”+currency+“”);//将余额显示在表中

out.println(“”+last_modifield+“”); //将上次操作时间显示在表中

out.println(“”);

}

}catch(SQLException e)

{

out.println(“发生异常:”+e.getMessage());

e.printStackTrace();

}finally{

if(rs!=null) rs.close();

if(stmt!=null) stmt.close();

if(conn!=null) conn.close();

}

%>

<%

String action=request.getParameter(“action”);//获取action操作

if(“a2b”.equals(action))

{

out.println(“业务:A向B转账200元。
”);

try

{

DriverManager.registerDriver(new com.mysql.jdbc.Driver());

conn=DriverManager.getConnection(“jdbc:mysql://localhost:3306/account”,“root”,“root”);

conn.setAutoCommit(false);//将自动提交设为false

stmt=conn.createStatement();

String sql1="UPDATE tb_currency SET currency=currency-200 WHERE account='A’and currency>=200 ";

int result1=stmt.executeUpdate(sql1);

out.println(“A账号扣款200元,结果:”+ (result1==1?“成功”:“失败”)+“
”);

String sql2=“UPDATE tb_currency SET currency=currency+200 WHERE account=‘B’”;

int result2=stmt.executeUpdate(sql2);

out.println(“B账号进款200元,结果:”+ (result2==1?“成功”:“失败”)+“
”);

if(result11 && result21)

{

conn.commit();//提交事务

out.println(“转账成功,事务提交。点此刷新账表”);

}else{

conn.rollback();//事务回滚

out.println(“转账失败,事务回滚。”);

}

}finally{

if(stmt!=null) stmt.close();

if(conn!=null) conn.close();

}

}else if(“b2a”.equals(action))

{

out.println(“业务:B向A转账200元。
”);

try

{

DriverManager.registerDriver(new com.mysql.jdbc.Driver());//注册驱动

conn=DriverManager.getConnection(“jdbc:mysql://localhost:3306/account”,“root”,“root”);//获取连接

conn.setAutoCommit(false);//将自动提交设为false

stmt=conn.createStatement();

String sql1="UPDATE tb_currency SET currency=currency-200 WHERE account='B’and currency>=200 ";

int result1=stmt.executeUpdate(sql1);

out.println(“B账号扣款200元,结果:”+ (result1==1?“成功”:“失败”)+“
”);

最后

“+ (result1==1?“成功”:“失败”)+”
");

最后

[外链图片转存中…(img-unIbvP1I-1719264129535)]

[外链图片转存中…(img-7AZLwAcx-1719264129536)]

[外链图片转存中…(img-jv8Cio1j-1719264129537)]

  • 13
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值