Affairs
Comprising a plurality of operational steps. If this operation is business transaction management, this multiple steps at the same time either succeed or fail at the same time.
Operation of the transaction
-
Open affairs
-
Commit the transaction
-
Roll back the transaction
Connection object to manage transactions
the java.sql.Connection interface is connected to a database object. It connects to a specific database (session). Execute SQL statement and return the results in the context of the connection.
- Open affairs
setAutoCommit ( boolean autoCommit) // This method is called parameter set to false, open affairs
- Commit the transaction
the commit () // When all sql are executing the transaction is committed
- Roll back the transaction
ROLLBACK () // roll back the transaction in the catch
Java Code Example
There follows a MySQL data table, using the Java program: id = 1 corresponding to the balance is decreased by 500, id = 2 corresponding to the increase in the balance 500
CREATE TABLE account ( ID the INT a PRIMARY KEY the AUTO_INCREMENT, - ID NAME VARCHAR ( 10 ), - the name Balance DOUBLE - Balance ); INSERT INTO account (NAME, balance) VALUES ('LeeHua', 1000), ('Tom', 1000);
A custom annotation for information connected to the database:
package my.view.util; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target (ElementType.TYPE) // annotations can at class @Retention (RetentionPolicy.RUNTIME) // annotation currently being described, will be retained to the class bytecode files, and read into the JVM public @ interface PropertiesAnnotation { /* URL */ public abstract String url(); / * User * / public abstract String User (); / * Code * / public abstract String password (); / * Driver package * / public abstract String Driver (); }
Define a utility class for registering drivers and database connection objects:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; @PropertiesAnnotation( url = "jdbc:mysql:///Study", user = "账号", password = "密码", driver = "com.mysql.jdbc.Driver" ) public class JdbcUtils02 { private static String url; private static String user; private static String password; private static String driver; / * File is read, only you need to read once to get these values. Annotations using reflection and using a static block * / static { // read the resource file to obtain the value. the try { // 1. Analytical annotation @ 1.1 JdbcUtils02 obtain bytecode file object class Class <JdbcUtils02> jdbcUtils02Class = JdbcUtils02. class ; // 2. Get the object on top of the annotation PropertiesAnnotation Annotation = jdbcUtils02Class.getAnnotation (PropertiesAnnotation. Class ); // Call the abstract methods defined in the notes to obtain the return value, assigned to the static member variables url = annotation.url (); user = annotation.user(); password = annotation.password(); driver = annotation.driver(); // 4. Register drive Class.forName (driver); } catch (ClassNotFoundException e) { e.printStackTrace (); } } /** * Get connected * @return 连接对象 */ public static Connection getConnection() throws SQLException { return DriverManager.getConnection(url, user, password); } }
With the above conditions, the operation of the data table:
- Database connection
Connection connection = JdbcUtils02.getConnection();
- After obtaining the database connection object, open affairs
connection.setAutoCommit(false);
- Open transaction actually creates a log file, the results of the implementation of SQL statements defined temporarily put his diary, if not wrong, commit the transaction, if an error, then it rolls back the transaction. Next, define dynamic SQL statements
String sql1 = "update account set balance = balance - ? where id = ?";
String sql2 = "update account set balance = balance + ? where id = ?"; - Well-defined SQL statements, then we must get the object execute dynamic SQL statements
PreparedStatement preparedStatement1 = connection.prepareStatement(sql1); PreparedStatement preparedStatement2 = connection.prepareStatement(sql2);
- Parameters passed to the dynamic SQL statement
// LeeHua account balance has been reduced 500 yuan preparedStatement1.setDouble (1,500 ); preparedStatement1.setInt(2,1); // Tom's account balance increase of 500 yuan preparedStatement2.setDouble (1,500 ); preparedStatement2.setInt(2,2);
- Everything is ready, this time you can execute SQL statements
preparedStatement1.executeUpdate();
preparedStatement2.executeUpdate(); - After the execution of SQL statements, if not wrong, then commit the transaction, which will change the recording time table
connection.commit();
- After executing the SQL statement, if there is an error, then it rolls back the transaction, this time, the record will delete diary, will not submit to the table, the table does not change the record
connection.rollback();
- Whether execute SQL statements, if there is an error, and finally need to free up resources, call custom releaseResources () method to release resources
releaseResources(preparedStatement2); releaseResources(preparedStatement1); releaseResources(connection);
- Defined releaseResources () method is as follows:
/** * Release resources * @Param t the resources to be released * @Param <T> object type of the resource to be released * / public static <T> void releaseResources (T T) { IF (T! = Null ) { the try { // by reflection, acquiring the object class Class <?> = aClass t.getClass (); // method object to obtain class object method, Close aClass.getMethod = ( "Close" ); // perform a method close.invoke (t); } catch (Exception e) { e.printStackTrace (); } } }
Implementation code to the data table operating as follows:
package my.view.jdbc; import my.view.util.JdbcUtils02; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; public class JdbcDemo09 { public static void main(String[] args) { Connection connection = null; PreparedStatement preparedStatement1 = null; PreparedStatement preparedStatement2 = null; the try { // 1. Get connected Connection = JdbcUtils02.getConnection (); // open transaction connection.setAutoCommit ( false ); // 2. Define SQL // 2.1 define SQL statements to reduce the account balance String SQL1 = "Update the Account Balance = Balance the SET - the WHERE the above mentioned id =??" ; // 2.2 define the account balance increased SQL statement String sql2 = "update account Balance = Balance + the WHERE the SET the above mentioned id = "?? ; // 3. Get to execute SQL statements subject preparedStatement1 = Connection.prepareStatement (SQL1); preparedStatement2 = connection.prepareStatement(sql2); // 4. Set the parameters // 4.1 LeeHua reduce the account balance 500 yuan preparedStatement1.setDouble (1,500 ); preparedStatement1.setInt ( 2,1 ); // 4.2 Tom's account balance increase of 500 yuan preparedStatement2.setDouble (1,500 ); preparedStatement2.setInt(2,2); // 5. execute SQL statements preparedStatement1.executeUpdate (); preparedStatement2.executeUpdate(); // 6. commit the transaction connection.commit (); } The catch (Exception E) { // 7. The transaction rollback the try { IF (Connection! = Null ) { connection.rollback(); } } catch (SQLException e1) { e1.printStackTrace (); } } The finally { // 8. The release resources releaseResources (preparedStatement2); releaseResources(preparedStatement1); releaseResources(connection); } } /** * Release resources * @Param t the resources to be released * @Param <T> object type of the resource to be released * / public static <T> void releaseResources (T T) { IF (T! = Null ) { the try { // by reflection, acquiring the object class Class <?> = aClass t.getClass (); // method object to obtain class object method, Close aClass.getMethod = ( "Close" ); // perform a method close.invoke (t); } catch (Exception e) { e.printStackTrace (); } } } }
Run the program to view the records in the table, found LeeHua account balance reduced by 500, Tom's account balance increased by 500.