Transaction processing in Java

zhaozj2021-02-12  183

In database operation, a transaction refers to an indivisible working unit consisting of one or more SQL statements updated by the database. Only when all operations in the transaction are all completed, the entire transaction can be submitted to the database. If there is an operation, the entire transaction must be revoked.

For example, in the bank's transfer transaction, assume that Zhang San forwards 1,000 yuan from its own account to Lee Si's account, the relevant SQL statement is as follows:

Update Account set monery = monry-1000 where name = 'zhangsan'

Update Account set monry = monry 1000 Where name = 'lisi'

This two statements must be processed as a completed transaction. This transaction can only be submitted only when both have been successfully executed. If there is a failure, the entire transaction must be undo.

3 ways of controlling transactions are provided in the Connection class:

(1) SetAutocommit (Boolean AutoCommit): Set whether you automatically submit a transaction;

(2) commit (); submit a transaction;

(3) rollback (); withdrawal transaction;

In the JDBC API, the default situation is automatically submitted to the transaction, that is, each SQL statement for the database represents a transaction. After the operation is successful, the system automatically calls commit () to submit, otherwise the Rollback () will be called. To undo the transaction.

In the JDBC API, you can prohibit automatic submission of transactions by calling SetAutocommit (False). Then you can make multiple update databases as a transaction. After all operations are complete, call commit () to make an overall commit. If one of the SQL operations fail, the commit () method is not executed, but the corresponding SQLException can be captured in the abnormal code block to invoke the Rollback () method to undo transaction.

Try {

Con = java.sql.driverManager.getConnection (DBURL, DBUSER, DBPASS);

Con.SetAutocommit (False);

STMT = con.createstatement ();

Stmt.executeUpdate ("Update Account Set Monry = MonERY-1000 WHERE Name = 'ZHANGSAN');

Stmt.executeUpdate ("Update Account Set Monry = MonERY 1000 WHERE Name = 'LISI');

C.Commit ();

} catch (exception ex) {

EX.PrintStackTrace ();

Try {

CON. ROLLBACK ();

} catch (exception e) {

E.PrintStackTrace ();

}

} finally {

Try {

Stmt.close ();

C. close ();

} catch (exception e) {

E.PrintStackTrace ();

}

}

转载请注明原文地址:https://www.9cbs.com/read-6476.html

New Post(0)