设置conn的setAutoCommit方法参数false 调用conn.commit()方法 随后在捕获异常后在catch段里添加coon.rollback()方法
1 package com.iwb.jdbc; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.SQLException; 6 import java.sql.Statement; 7 8 public class TransactionTest { 9 public static Connection getConnection(){ 10 Connection conn=null; 11 String url="jdbc:mysql://localhost:3306/bbs_user?" 12 +"user=root&password=123456&useUnicode=true&characterEncoding=UTF8"; 13 try { 14 Class.forName("com.mysql.jdbc.Driver"); 15 conn= DriverManager.getConnection(url); 16 } catch (Exception e) { 17 // TODO: handle exception 18 e.printStackTrace(); 19 } 20 return conn; 21 } 22 public static void insertUserData(Connection conn) throws SQLException{ 23 24 String sql="insert into bbs_user(id,username,password,gender,email,birthdate) " 25 + "values(10,‘yangyang‘,‘lili‘,1,‘[email protected]‘,‘1995-09-09‘)"; 26 Statement st=conn.createStatement(); 27 int count = st.executeUpdate(sql); 28 System.out.println("charu"+count+"tiao xinxi"); 29 30 } 31 public static void insertAddressData(Connection conn) throws SQLException{ 32 33 String sql="insert into bbs_messages(id,author,info,published)" + 34 "values(10,6,‘sssddddddddddddd‘,‘1998-09-09‘)"; 35 Statement st=conn.createStatement(); 36 int count = st.executeUpdate(sql); 37 System.out.println("charu"+count+"tiao xinxi"); 38 39 } 40 public static void main(String[] args) { 41 Connection conn=null; 42 try { 43 conn=getConnection(); 44 conn.setAutoCommit(false); 45 insertUserData(conn); 46 insertAddressData(conn); 47 48 conn.commit(); 49 } catch (SQLException e) { 50 // TODO Auto-generated catch block 51 System.out.println("yichang"); 52 e.printStackTrace(); 53 try { 54 conn.rollback(); 55 System.out.println("huigun"); 56 } catch (Exception e2) { 57 // TODO: handle exception 58 } 59 }finally{ 60 try { 61 if(conn!=null){ 62 conn.close(); 63 } 64 } catch (Exception e2) { 65 // TODO: handle exception 66 e2.printStackTrace(); 67 } 68 } 69 } 70 }
时间: 2024-10-08 03:00:39