1. 程式人生 > >事務的處理案例

事務的處理案例

where dstat div 事務 tar false cep style ive

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

事務的處理案例