30 jdbc transaction settings

What is a transaction

In plsql, we after performing CRUD, and not immediately written to the table, but to manually click the submit button submit button (f10), if you do not just submit code execution, you can click on the Rollback button (shift + f10).

In the commit and rollback FIG plsql:

 

 

 

Use jdbc affairs

In the background the project, if not set to automatically submit it defaults to automatically submit true. This causes a problem: Unsafe data.

For example, in eclipse, we did not write a jdbc connection settings automatically submitted, the code for the account transfer 1000 yuan from A's to B, the program is running, the charge from A successful implementation of the code, but to added code $ 1000 B exception was thrown.

We query table shows that 1000 yuan accounts indeed less A's, B's account but did not increase.

jdbc setting Affairs

The first step: Use it calls setAutoCommit after connecting to the database object creation (false) method pass false

Step Two: try try-catch block execution of a SQL statement, SQL statements added after the code: conn.commit (); // conn database connection object. Normal execution of SQL statements in the absence of reported anomalies

A third step, the catch try-catch block of executing SQL statements (SQLException e) added: conn.rollback (); which indicates if the SQL statement is executed reported abnormal, the rollback, the execution result is not written in the table .

commit () method is equivalent to the submit button, and rollback () method is equivalent to roll back button.

Complete the following example:

try {
			// 1. Load the driver class
			Class.forName(driver);
			// 2. Database objects connected to the specified
			conn = DriverManager.getConnection(url,username,password);
			// 3. Setting autocommit set to false
			conn.setAutoCommit(false);
			3 // Get sql command object
			stmt = conn.createStatement();
			// 4. Create a SQL command
			String sql = "insert into dept values ​​(80, 'chicken Academy', 'Beijing')";
			String sql2 = "select * from emp";
			// 5. execute SQL commands
			int i = stmt.executeUpdate (sql2); // -1 to indicate failure to return other number indicates the number of executed successfully.
			System.out.println ( "execution result:" + i);
			conn.commit();
		} catch (ClassNotFoundException e) {
			e.printStackTrace ();
		}catch(SQLException e){
			try {
				conn.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace ();
			}
			e.printStackTrace ();
		}finally {
			6 // Close streams
			try {
				if(stmt!=null) {
					stmt.close();
				}
			} catch (SQLException e) {
				e.printStackTrace ();
			}
			try {
				if(conn!=null) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace ();
			}
		}

  

Guess you like

Origin www.cnblogs.com/Scorpicat/p/12312862.html