JDBC03 uses JDBC to implement transaction submission and rollback [Calling methods in Connection to achieve transaction management]

Catalogue

1. Reuse methods in Connection

2 JDBC Transaction Management Classic Case

Review of common methods in 1 Connection classes

  1.1 Statement createStatement() throws SQLException;

Create a Statement instance (that is, create an SQL execution object)

  1.2 PreparedStatement prepareStatement(String sql) throws SQLException;

Create a PreparedStatement object (that is, create a precompiled SQL execution object)

  1.3 void setAutoCommit(boolean autoCommit) throws SQLException;

Set up automatic commit of transactions (false is to turn off automatic commit, true is to start automatic commit)

  1.4 void commit() throws SQLException;

Manual Submission of Transactions

  1.5 void rollback() throws SQLException;

Manual rollback of transactions

 

2. The classic case of transaction rollback: bank transfer case

Turn-out and turn-in are transactions. If the turn-out succeeds but fails, transaction rollbacks will be required. Otherwise, the turn-out balance will decrease but the turn-in balance will not increase.

Note: Transaction submission and rollback are invoked by the method provided by Connection; transactions are essentially dependent on the implementation of the database; and the method of Connection is essentially the invocation of the database transaction mechanism.

2.1 Transfer business without transaction control

Disadvantage: If the transfer succeeds, but the transfer fails, the transfer balance will decrease, but the transfer balance 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("Please enter a roll-out username:");
13         String outName = scanner.nextLine();
14         System.out.println("Please enter the amount of funds to be transferred:");
15         Double money = Double.parseDouble(scanner.nextLine());
16         System.out.println("Please enter the input username:");
17         String inName = scanner.nextLine();
18         System.out.println("The transfer account is:" + outName + "The amount transferred is:" + money + "Transferred to the account is:" + inName);
19         
20         
21         Connection conn = null;
22         try {
23             conn = DBUtil.getConnection(); // Instantiate connection objects
24             
25 //            conn.setAutoCommit(false); // Turn off automatic commit transaction function
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("Turn Out Success");
36             } else {
37                 System.out.println("Turn Out Failure");
38                 return; // The following statement is no longer executed; however, the following statement is not executed. finally The statement in the sentence will still be executed, because even if the sky falls down finally Statements in the
39             }
40             
41             System.out.println("======Partition line=======");
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("Turn to Success");
52 //                conn.commit(); // Turn-in and roll-out are successful in committing transactions
53             } else {
54                 System.out.println("Turn into failure");
55 //                conn.rollback(); // Roll back the transaction if the roll-out is successful or the roll-in is unsuccessful
56             }
57             
58 //            conn.setAutoCommit(true); // Open Autocommit Transaction
59             
60         } catch (Exception e) {
61             // TODO Auto-generated catch block
62             e.printStackTrace();
63         } finally {
64             System.out.println("I am finally The statement in");
65             try {
66                 DBUtil.closeConnection();
67             } catch (Exception e) {
68                 // TODO Auto-generated catch block
69                 e.printStackTrace();
70             }
71         }
72     }
73 }
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 );
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 Used to share data across threads
14      * ThreadLocal There is a Map inside. The key is the thread itself that needs to share data. value is the data that it needs to share.
15      */
16     private static ThreadLocal<Connection> tl; // Declare something similar to a warehouse
17     private static BasicDataSource dataSource; // Declare a database connection pool object
18     
19     // Static block of code, executed when the class is loaded, and executed only once
20     static {
21         tl = new ThreadLocal<Connection>(); // Instantiating Warehouse Objects
22         dataSource = new BasicDataSource(); // Instance database connection pool object
23 
24         Properties prop = new Properties(); // Create a Properties Object use (this object can be used to load the list of attributes in the configuration file)
25         InputStream is = DBUtil.class.getClassLoader().getResourceAsStream("config/mysql.properties"); // Read configuration file information
26         try {
27             prop.load(is); // Load the list of properties in the configuration file
28             
29             String driverClassName = prop.getProperty("driverClassName"); // Getting attribute information
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); // Initialize the database connection pool (that is, configure the relevant parameters of the database connection pool)
37             dataSource.setUrl(url);
38             dataSource.setUsername(username);
39             dataSource.setPassword(password);
40             dataSource.setMaxActive(maxActive);
41             dataSource.setMaxWait(maxWait);
42             
43             is.close(); // Close the input stream and release resources
44         } catch (IOException e) {
45             // TODO Auto-generated catch block
46             e.printStackTrace();
47         } 
48         
49     }
50     
51     /**
52      * Create connection objects (Note: Static methods can be invoked directly by class names)
53      * @return Connection object
54      * @throws Exception
55      */
56     public static Connection getConnection() throws Exception { 
57         try {
58             Connection conn = dataSource.getConnection(); // Create connection objects (create using database connection pools)
59             tl.set(conn); // Put the connection object in the warehouse
60             return conn; 
61         } catch (Exception e) {
62             // TODO Auto-generated catch block
63             e.printStackTrace();
64             throw e;
65         }
66     }
67     
68     /**
69      * Close the connection object (Note: Static methods can be called directly by class names)
70      * @throws Exception
71      */
72     public static void closeConnection() throws Exception {
73         Connection conn = tl.get(); // Remove the connection object from the warehouse
74         tl.remove(); // Empty warehouse
75         if(conn != null) { // Determine whether the connection object releases resources
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 }
java source code for 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 hao
3 # hou mian bu neng you kong ge
4 driverClassName=com.mysql.jdbc.Driver
5 url=jdbc:mysql://localhost:3306/test
6 username=root
7 password=182838
8 maxActive=100
9 maxWait=3000
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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 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>
maven dependency file

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("Please enter a roll-out username:");
14         String outName = scanner.nextLine();
15         System.out.println("Please enter the amount of funds to be transferred:");
16         Double money = Double.parseDouble(scanner.nextLine());
17         System.out.println("Please enter the input username:");
18         String inName = scanner.nextLine();
19         System.out.println("The transfer account is:" + outName + "The amount transferred is:" + money + "Transferred to the account is:" + inName);
20         
21         
22         Connection conn = null;
23         try {
24             conn = DBUtil.getConnection(); // Instantiate connection objects
25             
26             conn.setAutoCommit(false); // Turn off automatic commit transaction function
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("Turn Out Success");
37             } else {
38                 System.out.println("Turn Out Failure");
39                 return; // The following statement is no longer executed; however, the following statement is not executed. finally The statement in the sentence will still be executed, because even if the sky falls down finally Statements in the
40             }
41             
42             System.out.println("======Partition line=======");
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("Turn to Success");
53                 conn.commit(); // Turn-in and roll-out are successful in committing transactions
54             } else {
55                 System.out.println("Turn into failure");
56                 conn.rollback(); // Roll back the transaction if the roll-out is successful or the roll-in is unsuccessful
57             }
58             
59             conn.setAutoCommit(true); // Open Autocommit Transaction
60             
61         } catch (Exception e) {
62             // TODO Auto-generated catch block
63             try {
64                 conn.rollback(); // Transaction rollbacks are also required after exceptions are caught
65             } catch (SQLException e1) {
66                 // TODO Auto-generated catch block
67                 e1.printStackTrace();
68             } 
69             e.printStackTrace();
70         } finally {
71             System.out.println("I am finally The statement in");
72             try {
73                 DBUtil.closeConnection();
74             } catch (Exception e) {
75                 // TODO Auto-generated catch block
76                 e.printStackTrace();
77             }
78         }
79     }
80 }
java source code for transfer business

2.3 Encapsulate the automatic submission function, manual submission function and manual rollback function into a 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 Used to share data across threads
 14      * ThreadLocal There is a Map inside. The key is the thread itself that needs to share data. value is the data that it needs to share.
 15      */
 16     private static ThreadLocal<Connection> tl; // Declare something similar to a warehouse
 17     private static BasicDataSource dataSource; // Declare a database connection pool object
 18     
 19     // Static block of code, executed when the class is loaded, and executed only once
 20     static {
 21         tl = new ThreadLocal<Connection>(); // Instantiating Warehouse Objects
 22         dataSource = new BasicDataSource(); // Instance database connection pool object
 23 
 24         Properties prop = new Properties(); // Create a Properties Object use (this object can be used to load the list of attributes in the configuration file)
 25         InputStream is = DBUtil.class.getClassLoader().getResourceAsStream("config/mysql.properties"); // Read configuration file information
 26         try {
 27             prop.load(is); // Load the list of properties in the configuration file
 28             
 29             String driverClassName = prop.getProperty("driverClassName"); // Getting attribute information
 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); // Initialize the database connection pool (that is, configure the relevant parameters of the database connection pool)
 37             dataSource.setUrl(url);
 38             dataSource.setUsername(username);
 39             dataSource.setPassword(password);
 40             dataSource.setMaxActive(maxActive);
 41             dataSource.setMaxWait(maxWait);
 42             
 43             is.close(); // Close the input stream and release resources
 44         } catch (IOException e) {
 45             // TODO Auto-generated catch block
 46             e.printStackTrace();
 47         } 
 48         
 49     }
 50     
 51     /**
 52      * Create connection objects (Note: Static methods can be invoked directly by class names)
 53      * @return Connection object
 54      * @throws Exception
 55      */
 56     public static Connection getConnection() throws Exception { 
 57         try {
 58             Connection conn = dataSource.getConnection(); // Create connection objects (create using database connection pools)
 59             tl.set(conn); // Put the connection object in the warehouse
 60             return conn; 
 61         } catch (Exception e) {
 62             // TODO Auto-generated catch block
 63             e.printStackTrace();
 64             throw e;
 65         }
 66     }
 67     
 68     /**
 69      * Close the connection object (Note: Static methods can be called directly by class names)
 70      * @throws Exception
 71      */
 72     public static void closeConnection() throws Exception {
 73         Connection conn = tl.get(); // Remove the connection object from the warehouse
 74         tl.remove(); // Empty warehouse
 75         if(conn != null) { // Determine whether the connection object releases resources
 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      * Turn off JDBC's automatic commit transaction function before executing SQL statements
 88      * @throws SQLException
 89      */
 90     public static void tansBegin() throws SQLException {
 91         try {
 92             tl.get().setAutoCommit(false); // Get the connection object from the warehouse and call it setAutoCommit To turn off the automatic commit transaction function
 93         } catch(SQLException e) {
 94             e.printStackTrace();
 95             throw e;
 96         }
 97     }
 98     
 99     /**
100      * Manual rollback function
101      * @throws SQLException
102      */
103     public static void transBack() throws SQLException {
104         tl.get().rollback(); // Get the connection object from the warehouse and call it rollback Implementing transaction rollback operations
105         tl.get().setAutoCommit(true); // Rollback Start Transaction Autocommit Function
106     }
107     
108     /**
109      * Manual submission function
110      * @throws SQLException
111      */
112     public static void transCommit() throws SQLException {
113         tl.get().commit(); // Get the connection object from the warehouse and call it commit Implementing transaction commit operations
114         tl.get().setAutoCommit(true); // Start transaction autocommit after commit
115     }
116 
117 }
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("Please enter a roll-out username:");
14         String outName = scanner.nextLine();
15         System.out.println("Please enter the amount of funds to be transferred:");
16         Double money = Double.parseDouble(scanner.nextLine());
17         System.out.println("Please enter the input username:");
18         String inName = scanner.nextLine();
19         System.out.println("The transfer account is:" + outName + "The amount transferred is:" + money + "Transferred to the account is:" + inName);
20         
21         
22         Connection conn = null;
23         try {
24             conn = DBUtil.getConnection(); // Instantiate connection objects
25             
26             DBUtil.tansBegin(); // Turn off automatic commit transaction function
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("Turn Out Success");
37             } else {
38                 System.out.println("Turn Out Failure");
39                 return; // The following statement is no longer executed; however, the following statement is not executed. finally The statement in the sentence will still be executed, because even if the sky falls down finally Statements in the
40             }
41             
42             System.out.println("======Partition line=======");
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("Turn to Success");
53                 DBUtil.transCommit(); // Turn-in and roll-out are successful in committing transactions
54             } else {
55                 System.out.println("Turn into failure");
56                 DBUtil.transBack(); // Roll back the transaction if the roll-out is successful or the roll-in is unsuccessful
57             }
58             
59         } catch (Exception e) {
60             // TODO Auto-generated catch block
61             try {
62                 DBUtil.transBack();// Transaction rollbacks are also required after exceptions are caught
63             } catch (SQLException e1) {
64                 // TODO Auto-generated catch block
65                 e1.printStackTrace();
66             } 
67             e.printStackTrace();
68         } finally {
69             System.out.println("I am finally The statement in");
70             try {
71                 DBUtil.closeConnection();
72             } catch (Exception e) {
73                 // TODO Auto-generated catch block
74                 e.printStackTrace();
75             }
76         }
77     }
78 }
Transfer business java source code

Keywords: Java SQL Database MySQL

Added by JParishy on Sun, 16 Jun 2019 02:46:35 +0300