简单事务的回滚

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了简单事务的回滚相关的知识,希望对你有一定的参考价值。

设置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 }
View Code

 

以上是关于简单事务的回滚的主要内容,如果未能解决你的问题,请参考以下文章

spring中事务的回滚

如何在事务上设置挂起的回滚?

Spring transactions - 新事务中的异常导致父事务中的回滚

Oracle 事务操作(事务的回滚与提交)

SSM-MyBatis-09:Mybatis中SqlSession的close为什么能造成事务的回滚

mysql命令行下怎样实现数据的回滚操作