Table of Contents
 1.1 Statement createStatement() throws SQLException;
 1.2 PreparedStatement prepareStatement(String sql) throws SQLException ;
 1.3 void setAutoCommit(boolean autoCommit) throws SQLException;
  1.4 void commit() throws SQLException;
 1.5 void rollback() throws SQLException;
2 Classic case where transaction rollback is required: Bank transfer case
  2.2 Transfer business using transaction control
 2.3 Encapsulate the automatic submission function, manual submission function, and manual rollback function into In one class
Home Java javaTutorial JDBC implementation of transaction submission and rollback examples

JDBC implementation of transaction submission and rollback examples

Jul 20, 2017 pm 07:05 PM
jdbc affairs

1. Review of commonly used methods in the Connection class

 1.1 Statement createStatement() throws SQLException;

  Create a Statement instance (ie: create a SQL execution object)

 1.2 PreparedStatement prepareStatement(String sql) throws SQLException ;

  Create a PreparedStatement object (ie: create a precompiled SQL execution object)

 1.3 void setAutoCommit(boolean autoCommit) throws SQLException;

  Set the automatic submission of the transaction (false means to turn off automatic submission, true to start automatic submission)

  1.4 void commit() throws SQLException;

   Manually commit transaction

 1.5 void rollback() throws SQLException;

   Manual rollback of transaction

2 Classic case where transaction rollback is required: Bank transfer case

 Transfer out and transfer in are one transaction. If the transfer out is successful but the transfer in fails, the transaction needs to be rolled back. Otherwise, the balance of the transferor will decrease but the balance of the transferor will not increase.

 Note: Submission of the transaction Rollback is called through the method provided by Connection; essentially the transaction still relies on the implementation of the database; The method of Connection essentially calls the database transaction mechanism.

  2.1 Not using transaction control Transfer business

Disadvantages: If the transfer is successful, but the transfer fails, the balance of the transferor will be reduced, but the balance of the transferor will remain unchanged

Project structure chart

   

 1 package cn.xiangxu.entity; 2  3 import java.sql.Connection; 4 import java.sql.PreparedStatement; 5 import java.util.Scanner; 6  7 import cn.xiangxu.tools.DBUtil; 8  9 public class Test {10     public static void main(String[] args) {11         Scanner scanner = new Scanner(System.in);12         System.out.println("请输入转出用户名:");13         String outName = scanner.nextLine();14         System.out.println("请输入需要转出的资金额度:");15         Double money = Double.parseDouble(scanner.nextLine());16         System.out.println("请输入转入用户名:");17         String inName = scanner.nextLine();18         System.out.println("转出账户为:" + outName + "转出金额为:" + money + "转入账户为:" + inName);19         20         21         Connection conn = null;22         try {23             conn = DBUtil.getConnection(); // 实例化连接对象24             25 //            conn.setAutoCommit(false); // 关闭自动提交事务功能26             27             String sql = "UPDATE client "28                     + "SET account = account - ? " 
29                     + "WHERE name = ? ";30             PreparedStatement ps = conn.prepareStatement(sql);31             ps.setDouble(1, money);32             ps.setString(2, outName);33             Integer rs = ps.executeUpdate();34             if(rs > 0) {35                 System.out.println("转出成功");36             } else {37                 System.out.println("转出失败");38                 return; // 转出失败跳出函数,不再执行下面的语句;但是finally中的语句还是会执行的,因为就算天塌下来finally中的语句都会执行39             }40             41             System.out.println("======分割线=======");42             43             String sql_in = "UPDATE client "44                     + "SET account = account + ? " 
45                     + "WHERE name = ? ";46             PreparedStatement ps_in = conn.prepareStatement(sql_in);47             ps_in.setDouble(1, money);48             ps_in.setString(2, inName);49             Integer judge_in = ps_in.executeUpdate();50             if(judge_in > 0) {51                 System.out.println("转入成功");52 //                conn.commit(); // 转出、转入都成功就提交事务53             } else {54                 System.out.println("转入失败");55 //                conn.rollback(); // 转出成功、转入失败就回滚事务56             }57             58 //            conn.setAutoCommit(true); // 打开自动提交事务59             60         } catch (Exception e) {61             // TODO Auto-generated catch block62             e.printStackTrace();63         } finally {64             System.out.println("我是finally中的语句哟");65             try {66                 DBUtil.closeConnection();67             } catch (Exception e) {68                 // TODO Auto-generated catch block69                 e.printStackTrace();70             }71         }72     }73 }
Copy after login
Transfer business java source code
1 CREATE TABLE client  (2     id INT (10)  PRIMARY KEY,3     name VARCHAR (10),4     pwd VARCHAR (10),5     account INT (20)6 );
Copy after login
SQL statement
 1 package cn.xiangxu.tools; 2  3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.sql.Connection; 6 import java.sql.SQLException; 7 import java.util.Properties; 8  9 import org.apache.commons.dbcp.BasicDataSource;10 11 public class DBUtil {12     /*13      * ThreadLocal用于线程跨方法共享数据使用14      * ThreadLocal内部有一个Map,  key为需要共享数据的线程本身,value就是其需要共享的数据15      */16     private static ThreadLocal<Connection> tl; // 声明一个类似于仓库的东西17     private static BasicDataSource dataSource; // 声明一个数据库连接池对象18     19     // 静态代码块,在类加载的时候执行,而且只执行一次20     static {21         tl = new ThreadLocal<Connection>(); // 实例化仓库对象22         dataSource = new BasicDataSource(); // 实例数据库连接池对象23 24         Properties prop = new Properties(); // 创建一个Properties对象用(该对象可以用来加载配置文件中的属性列表)25         InputStream is = DBUtil.class.getClassLoader().getResourceAsStream("config/mysql.properties"); // 读取配置文件信息26         try {27             prop.load(is); // 加载配置文件中的属性列表28             29             String driverClassName = prop.getProperty("driverClassName"); // 获取属性信息30             String url = prop.getProperty("url");31             String username = prop.getProperty("username");32             String password = prop.getProperty("password");33             Integer maxActive = Integer.parseInt(prop.getProperty("maxActive"));34             Integer maxWait = Integer.parseInt(prop.getProperty("maxWait"));35             36             dataSource.setDriverClassName(driverClassName); // 初始化数据库连接池(即:配置数据库连接池的先关参数)37             dataSource.setUrl(url);38             dataSource.setUsername(username);39             dataSource.setPassword(password);40             dataSource.setMaxActive(maxActive);41             dataSource.setMaxWait(maxWait);42             43             is.close(); // 关闭输入流,释放资源44         } catch (IOException e) {45             // TODO Auto-generated catch block46             e.printStackTrace();47         } 
48         49     }50     51     /**52      * 创建连接对象(注意:静态方法可以直接通过类名来调用)53      * @return 连接对象54      * @throws Exception55      */56     public static Connection getConnection() throws Exception { 
57         try {58             Connection conn = dataSource.getConnection(); // 创建连接对象(利用数据库连接池进行创建)59             tl.set(conn); // 将连接对象放到仓库中60             return conn; 
61         } catch (Exception e) {62             // TODO Auto-generated catch block63             e.printStackTrace();64             throw e;65         }66     }67     68     /**69      * 关闭连接对象(注意:静态方法可以通过类名直接调用)70      * @throws Exception71      */72     public static void closeConnection() throws Exception {73         Connection conn = tl.get(); // 从仓库中取出连接对象74         tl.remove(); // 清空仓库75         if(conn != null) { // 判断连接对象是否释放资源76             try {77                 conn.close();78             } catch (Exception e) {79                 // TODO Auto-generated catch block80                 e.printStackTrace();81                 throw e;82             }83         }84     }85 86 }
Copy after login
java source code of database connection pool
1 # zhe shi zhu shi , yi ban bu yong zhong wen 
2 # deng hao liang bian mei you kong ge, mo wei mei you fen hao3 # hou mian bu neng you kong ge4 driverClassName=com.mysql.jdbc.Driver5 url=jdbc:mysql://localhost:3306/test6 username=root7 password=1828388 maxActive=1009 maxWait=3000
Copy after login
Database information file
 1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 "> 2   <modelVersion>4.0.0</modelVersion> 3   <groupId>cn.xiangxu</groupId> 4   <artifactId>testJDBC</artifactId> 5   <version>0.0.1-SNAPSHOT</version> 6   <dependencies> 7       <dependency> 8           <groupId>mysql</groupId> 9           <artifactId>mysql-connector-java</artifactId>10           <version>5.1.37</version>11       </dependency>12       <dependency>13           <groupId>junit</groupId>14           <artifactId>junit</artifactId>15           <version>4.12</version>16       </dependency>17       <dependency>18           <groupId>commons-dbcp</groupId>19           <artifactId>commons-dbcp</artifactId>20           <version>1.4</version>21       </dependency>22   </dependencies>23 </project>
Copy after login
maven dependency files

  2.2 Transfer business using transaction control

 1 package cn.xiangxu.entity; 2  3 import java.sql.Connection; 4 import java.sql.PreparedStatement; 5 import java.sql.SQLException; 6 import java.util.Scanner; 7  8 import cn.xiangxu.tools.DBUtil; 9 10 public class Test {11     public static void main(String[] args) {12         Scanner scanner = new Scanner(System.in);13         System.out.println("请输入转出用户名:");14         String outName = scanner.nextLine();15         System.out.println("请输入需要转出的资金额度:");16         Double money = Double.parseDouble(scanner.nextLine());17         System.out.println("请输入转入用户名:");18         String inName = scanner.nextLine();19         System.out.println("转出账户为:" + outName + "转出金额为:" + money + "转入账户为:" + inName);20         21         22         Connection conn = null;23         try {24             conn = DBUtil.getConnection(); // 实例化连接对象25             26             conn.setAutoCommit(false); // 关闭自动提交事务功能27             28             String sql = "UPDATE client "29                     + "SET account = account - ? " 
30                     + "WHERE name = ? ";31             PreparedStatement ps = conn.prepareStatement(sql);32             ps.setDouble(1, money);33             ps.setString(2, outName);34             Integer rs = ps.executeUpdate();35             if(rs > 0) {36                 System.out.println("转出成功");37             } else {38                 System.out.println("转出失败");39                 return; // 转出失败跳出函数,不再执行下面的语句;但是finally中的语句还是会执行的,因为就算天塌下来finally中的语句都会执行40             }41             42             System.out.println("======分割线=======");43             44             String sql_in = "UPDATE client "45                     + "SET account = account + ? " 
46                     + "WHERE name = ? ";47             PreparedStatement ps_in = conn.prepareStatement(sql_in);48             ps_in.setDouble(1, money);49             ps_in.setString(2, inName);50             Integer judge_in = ps_in.executeUpdate();51             if(judge_in > 0) {52                 System.out.println("转入成功");53                 conn.commit(); // 转出、转入都成功就提交事务54             } else {55                 System.out.println("转入失败");56                 conn.rollback(); // 转出成功、转入失败就回滚事务57             }58             59             conn.setAutoCommit(true); // 打开自动提交事务60             61         } catch (Exception e) {62             // TODO Auto-generated catch block63             try {64                 conn.rollback(); // 捕获到异常后也需要进行事务回滚65             } catch (SQLException e1) {66                 // TODO Auto-generated catch block67                 e1.printStackTrace();68             } 
69             e.printStackTrace();70         } finally {71             System.out.println("我是finally中的语句哟");72             try {73                 DBUtil.closeConnection();74             } catch (Exception e) {75                 // TODO Auto-generated catch block76                 e.printStackTrace();77             }78         }79     }80 }
Copy after login
Java source code of transfer business

 2.3 Encapsulate the automatic submission function, manual submission function, and manual rollback function into In one class

  1 package cn.xiangxu.tools;  2   3 import java.io.IOException;  4 import java.io.InputStream;  5 import java.sql.Connection;  6 import java.sql.SQLException;  7 import java.util.Properties;  8   9 import org.apache.commons.dbcp.BasicDataSource; 10  11 public class DBUtil { 12     /* 13      * ThreadLocal用于线程跨方法共享数据使用 14      * ThreadLocal内部有一个Map,  key为需要共享数据的线程本身,value就是其需要共享的数据 15      */ 16     private static ThreadLocal<Connection> tl; // 声明一个类似于仓库的东西 17     private static BasicDataSource dataSource; // 声明一个数据库连接池对象 18      19     // 静态代码块,在类加载的时候执行,而且只执行一次 20     static { 21         tl = new ThreadLocal<Connection>(); // 实例化仓库对象 22         dataSource = new BasicDataSource(); // 实例数据库连接池对象 23  24         Properties prop = new Properties(); // 创建一个Properties对象用(该对象可以用来加载配置文件中的属性列表) 25         InputStream is = DBUtil.class.getClassLoader().getResourceAsStream("config/mysql.properties"); // 读取配置文件信息 26         try { 27             prop.load(is); // 加载配置文件中的属性列表 28              29             String driverClassName = prop.getProperty("driverClassName"); // 获取属性信息 30             String url = prop.getProperty("url"); 31             String username = prop.getProperty("username"); 32             String password = prop.getProperty("password"); 33             Integer maxActive = Integer.parseInt(prop.getProperty("maxActive")); 34             Integer maxWait = Integer.parseInt(prop.getProperty("maxWait")); 35              36             dataSource.setDriverClassName(driverClassName); // 初始化数据库连接池(即:配置数据库连接池的先关参数) 37             dataSource.setUrl(url); 38             dataSource.setUsername(username); 39             dataSource.setPassword(password); 40             dataSource.setMaxActive(maxActive); 41             dataSource.setMaxWait(maxWait); 42              43             is.close(); // 关闭输入流,释放资源 44         } catch (IOException e) { 45             // TODO Auto-generated catch block 46             e.printStackTrace(); 47         } 
 48          49     } 50      51     /** 52      * 创建连接对象(注意:静态方法可以直接通过类名来调用) 53      * @return 连接对象 54      * @throws Exception 55      */ 56     public static Connection getConnection() throws Exception { 
 57         try { 58             Connection conn = dataSource.getConnection(); // 创建连接对象(利用数据库连接池进行创建) 59             tl.set(conn); // 将连接对象放到仓库中 60             return conn; 
 61         } catch (Exception e) { 62             // TODO Auto-generated catch block 63             e.printStackTrace(); 64             throw e; 65         } 66     } 67      68     /** 69      * 关闭连接对象(注意:静态方法可以通过类名直接调用) 70      * @throws Exception 71      */ 72     public static void closeConnection() throws Exception { 73         Connection conn = tl.get(); // 从仓库中取出连接对象 74         tl.remove(); // 清空仓库 75         if(conn != null) { // 判断连接对象是否释放资源 76             try { 77                 conn.close(); 78             } catch (Exception e) { 79                 // TODO Auto-generated catch block 80                 e.printStackTrace(); 81                 throw e; 82             } 83         } 84     } 85      86     /** 87      * 在执行SQL语句前关闭JDBC的自动提交事务功能 88      * @throws SQLException 89      */ 90     public static void tansBegin() throws SQLException { 91         try { 92             tl.get().setAutoCommit(false); // 从仓库中获取连接对象并调用setAutoCommit来关闭自动提交事务功能 93         } catch(SQLException e) { 94             e.printStackTrace(); 95             throw e; 96         } 97     } 98      99     /**100      * 手动回滚功能101      * @throws SQLException102      */103     public static void transBack() throws SQLException {104         tl.get().rollback(); // 从仓库中获取连接对象并调用rollback来实现事务回滚操作105         tl.get().setAutoCommit(true); // 回滚启动事务自动提交功能106     }107     108     /**109      * 手动提交功能110      * @throws SQLException111      */112     public static void transCommit() throws SQLException {113         tl.get().commit(); // 从仓库中获取连接对象并调用commit来实现事务提交操作114         tl.get().setAutoCommit(true); // 提交后启动事务自动提交功能115     }116 117 }
Copy after login
DBUtil
 1 package cn.xiangxu.entity; 2  3 import java.sql.Connection; 4 import java.sql.PreparedStatement; 5 import java.sql.SQLException; 6 import java.util.Scanner; 7  8 import cn.xiangxu.tools.DBUtil; 9 10 public class Test {11     public static void main(String[] args) {12         Scanner scanner = new Scanner(System.in);13         System.out.println("请输入转出用户名:");14         String outName = scanner.nextLine();15         System.out.println("请输入需要转出的资金额度:");16         Double money = Double.parseDouble(scanner.nextLine());17         System.out.println("请输入转入用户名:");18         String inName = scanner.nextLine();19         System.out.println("转出账户为:" + outName + "转出金额为:" + money + "转入账户为:" + inName);20         21         22         Connection conn = null;23         try {24             conn = DBUtil.getConnection(); // 实例化连接对象25             26             DBUtil.tansBegin(); // 关闭自动提交事务功能27             28             String sql = "UPDATE client "29                     + "SET account = account - ? " 
30                     + "WHERE name = ? ";31             PreparedStatement ps = conn.prepareStatement(sql);32             ps.setDouble(1, money);33             ps.setString(2, outName);34             Integer rs = ps.executeUpdate();35             if(rs > 0) {36                 System.out.println("转出成功");37             } else {38                 System.out.println("转出失败");39                 return; // 转出失败跳出函数,不再执行下面的语句;但是finally中的语句还是会执行的,因为就算天塌下来finally中的语句都会执行40             }41             42             System.out.println("======分割线=======");43             44             String sql_in = "UPDATE client "45                     + "SET account = account + ? " 
46                     + "WHERE name = ? ";47             PreparedStatement ps_in = conn.prepareStatement(sql_in);48             ps_in.setDouble(1, money);49             ps_in.setString(2, inName);50             Integer judge_in = ps_in.executeUpdate();51             if(judge_in > 0) {52                 System.out.println("转入成功");53                 DBUtil.transCommit(); // 转出、转入都成功就提交事务54             } else {55                 System.out.println("转入失败");56                 DBUtil.transBack(); // 转出成功、转入失败就回滚事务57             }58             59         } catch (Exception e) {60             // TODO Auto-generated catch block61             try {62                 DBUtil.transBack();// 捕获到异常后也需要进行事务回滚63             } catch (SQLException e1) {64                 // TODO Auto-generated catch block65                 e1.printStackTrace();66             } 
67             e.printStackTrace();68         } finally {69             System.out.println("我是finally中的语句哟");70             try {71                 DBUtil.closeConnection();72             } catch (Exception e) {73                 // TODO Auto-generated catch block74                 e.printStackTrace();75             }76         }77     }78 }
Copy after login
Transfer business java source code

The above is the detailed content of JDBC implementation of transaction submission and rollback examples. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

After Java8 (291), TLS1.1 is disabled and JDBC cannot connect to SqlServer2008 using SSL. How to solve the problem? After Java8 (291), TLS1.1 is disabled and JDBC cannot connect to SqlServer2008 using SSL. How to solve the problem? May 16, 2023 pm 11:55 PM

After Java8-291, TLS1.1 is disabled, so that JDBC cannot connect to SqlServer2008 using SSL. What should I do? The following is the solution to modify the java.security file 1. Find the java.security file of jre. If it is jre, go to {JAVA_HOME}/jre/ In lib/security, for example????C:\ProgramFiles\Java\jre1.8.0_301\lib\security. If it is the Eclipse green installation-free portable version, search for java.security in the installation folder, such as????xxx\plugins \org

Lock wait timeout exceeded; try restarting transaction - How to solve MySQL error: transaction wait timeout Lock wait timeout exceeded; try restarting transaction - How to solve MySQL error: transaction wait timeout Oct 05, 2023 am 08:46 AM

Lockwaittimeoutexceeded;tryrestartingtransaction - How to solve the MySQL error: transaction wait timeout. When using the MySQL database, you may sometimes encounter a common error: Lockwaittimeoutexceeded;tryrestartingtransaction. This error indicates that the transaction wait timeout. This error usually occurs when

MySQL transaction processing: the difference between automatic submission and manual submission MySQL transaction processing: the difference between automatic submission and manual submission Mar 16, 2024 am 11:33 AM

MySQL transaction processing: the difference between automatic submission and manual submission. In the MySQL database, a transaction is a set of SQL statements. Either all executions are successful or all executions fail, ensuring the consistency and integrity of the data. In MySQL, transactions can be divided into automatic submission and manual submission. The difference lies in the timing of transaction submission and the scope of control over the transaction. The following will introduce the difference between automatic submission and manual submission in detail, and give specific code examples to illustrate. 1. Automatically submit in MySQL, if it is not displayed

PHP PDO Tutorial: An Advanced Guide from Basics to Mastery PHP PDO Tutorial: An Advanced Guide from Basics to Mastery Feb 19, 2024 pm 06:30 PM

1. Introduction to PDO PDO is an extension library of PHP, which provides an object-oriented way to operate the database. PDO supports a variety of databases, including Mysql, postgresql, oracle, SQLServer, etc. PDO enables developers to use a unified API to operate different databases, which allows developers to easily switch between different databases. 2. PDO connects to the database. To use PDO to connect to the database, you first need to create a PDO object. The constructor of the PDO object receives three parameters: database type, host name, database username and password. For example, the following code creates an object that connects to a mysql database: $dsn="mysq

How to implement JDBC batch insert in Java How to implement JDBC batch insert in Java May 18, 2023 am 10:02 AM

1. Explain that in JDBC, the executeBatch method can execute multiple dml statements in batches, and the efficiency is much higher than executing executeUpdate individually. What is the principle? How to implement batch execution in mysql and oracle? This article will introduce to you the principle behind this. 2. Experiment introduction This experiment will be carried out through the following three steps: a. Record the time consuming of jdbc batch execution and single execution in mysql; b. Record the time consuming of jdbc batch execution and single execution in oracle; c. Record the batch execution and single execution of oracleplsql. The execution time-consuming related java and database versions are as follows: Java17, Mysql8, Oracle

Java Errors: JDBC Errors, How to Solve and Avoid Java Errors: JDBC Errors, How to Solve and Avoid Jun 24, 2023 pm 02:40 PM

With the widespread application of Java, JDBC errors often occur when Java programs connect to databases. JDBC (JavaDatabaseConnectivity) is a programming interface in Java used to connect to a database. Therefore, a JDBC error is an error encountered when a Java program interacts with a database. Here are some of the most common JDBC errors and how to solve and avoid them. ClassNotFoundException This is the most common JDBC

Analysis of solutions to transaction management problems encountered in MongoDB technology development Analysis of solutions to transaction management problems encountered in MongoDB technology development Oct 08, 2023 am 08:15 AM

Analysis of solutions to transaction management problems encountered in MongoDB technology development As modern applications become more and more complex and large, the transaction processing requirements for data are also getting higher and higher. As a popular NoSQL database, MongoDB has excellent performance and scalability in data management. However, MongoDB is relatively weak in data consistency and transaction management, posing challenges to developers. In this article, we will explore the transaction management issues encountered in MongoDB development and propose some solutions.

The principles and application scenarios of MySQL transactions The principles and application scenarios of MySQL transactions Mar 02, 2024 am 09:51 AM

The principle and application scenarios of MySQL transactions In the database system, a transaction is a set of SQL operations. These operations are either all executed successfully or all fail and are rolled back. As a commonly used relational database management system, MySQL supports transaction characteristics and can ensure that the data in the database is consistent, isolated, durable and atomic. This article will start with the basic principles of MySQL transactions, introduce its application scenarios, and provide specific code examples for readers' reference. The principle of MySQL transactions: My

See all articles