package cn.sasa.tran01; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public class testJDBCTran { public static void main(String[] args) { Connection conn = null; PreparedStatement pstate = null; PreparedStatement pstate2 = null; try { //mysql的事务默认是自动执行的 //注册驱动 Class.forName("com.mysql.jdbc.Driver"); //获得连接对象 conn = DriverManager.getConnection("jdbc:mysql://192.168.0.207:3306/mydb", "root", "Console.Write21"); //设置手动执行事务 conn.setAutoCommit(false); //获得执行对象 String sql = "insert into account (name,money) values ('aaaaaaaaaaaaaaaaaaa',200)"; pstate = conn.prepareStatement(sql); //执行 int rs = pstate.executeUpdate(); String sql2 = "insert into account (name,money) values ('bb',300)"; pstate2 = conn.prepareStatement(sql2); int rs2 = pstate2.executeUpdate(); if(rs>0&&rs2>0) { conn.commit();//提交事务 System.out.println("ok"); }else { conn.rollback();//回滚事务 System.out.println("-1"); } }catch(Exception e) { try { conn.rollback(); System.out.println("-2"); } catch (SQLException e1) { e1.printStackTrace(); }//回滚事务 }finally { try { if(pstate !=null) pstate.close(); if(pstate2 !=null) pstate2.close(); if(conn !=null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }