码迷,mamicode.com
首页 > 其他好文 > 详细

事务的处理案例

时间:2017-05-20 20:05:07      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:mit   comm   null   for   cat   sys   tco   ring   cut   

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

}

 

事务的处理案例

标签:mit   comm   null   for   cat   sys   tco   ring   cut   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!