首页 > 其他 > 详细

事务的处理案例

时间:2017-05-20 19:53:06      阅读:331      评论:0      收藏:0      [点我收藏+]
package com.lianxi;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Testzhuan {
    public static void main(String[] args) throws Exception {
        send(1, 2, 1);
    }
    static{
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    
    public static void send(int src,int target,int num) throws Exception{
        Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/boooks","root","tiger");
        PreparedStatement ps=null;
        PreparedStatement ps1=null;
        try{
            conn.setAutoCommit(false);
            //先减钱
             ps=conn.prepareStatement("update account set remain=remain-"+num+" where accountid=?");
            ps.setInt(1, src);
            ps.execute();
            int i=9/0;
            //加钱
             ps1=conn.prepareStatement("update account set remain=remain+"+num+" where accountid=?");
            ps1.setInt(1, target);
            ps1.execute();
            conn.commit();
        }catch(Exception e){
            conn.rollback();
            System.out.println("转账失败");
        }finally{
            ps.close();
            ps1.close();
            conn.close();
        }
        
    }

}

 

事务的处理案例

原文:http://www.cnblogs.com/zyy1130/p/6882966.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!