jdbc的简单事务_jdbcjdbc的简单事务_jdbc_02

 1 package com.kuang.test; 2  3 import org.junit.Test; 4  5 import java.sql.Connection; 6 import java.sql.DriverManager; 7 import java.sql.SQLException; 8  9 public class TestJDBC3 {10 11     @Test12     public void test() throws ClassNotFoundException, SQLException {13         //配置信息14         String url="jdbc:mysql://10.10.18.6:3306/zhoutest?useUnicode=true&characterEncoding=utf-8";15         String username="root";16         String password="root";17 18         Connection connection = null;19 20         try{21             //1 加载驱动22             Class.forName("com.mysql.jdbc.Driver");23             //2 连接数据库24             connection = DriverManager.getConnection(url, username, password);25             //开启事务,很重要26             connection.setAutoCommit(false);27             String sql = "UPDATE account set money=money-100 where name='A'";28             connection.prepareStatement(sql).executeUpdate();29 30             //制造错误31             //int i = 1/0;32 33             String sql2 = "UPDATE account set money=money+100 where name='B'";34             connection.prepareStatement(sql2).executeUpdate();35 36             connection.commit();37             System.out.println("提交成功");38         }catch (Exception e){39 40             try {41                 connection.rollback();42             } catch (SQLException ex) {43                 ex.printStackTrace();44             }45 46 47             e.printStackTrace();48         }finally {49             connection.close();50         }51 52     }53 }

View Code