事务的处理案例
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(); } } }