Distributed Transaction combat (b) - the basic concept of a transaction

1 What is a transaction

One kind of 可靠、一致的way, the program access unit and the operation data in the database.

2 ACID properties

Not arbitrary sequence of operation of the database is a database transaction. Database transaction has the following four characteristics, known as the ACID properties is customary.

  • Atomicity (Atomicity): the transaction is performed as a whole, in the operation of the database contained therein are either all executed or not executed
  • Consistency (Consistency): Services should ensure that the state of the database from one consistent state to another consistent state. Meaning consistent state of data in the database integrity constraints should be met
  • Isolation (Isolation): concurrent execution of multiple transactions, executing a transaction should not affect the execution of other transactions
  • Persistent (Durability): transaction has been submitted to modify the database should be permanently stored in the database

3 Case

Someone to use electronic money to buy something at the store $ 100, including at least two operations:

  • The reduction of 100 yuan's account
  • Store accounts increased 100 yuan

Transactional database management system (transactional DBMS) is to ensure that more than two operations (the whole "transaction") can be completed, or canceled together; otherwise, 100 yuan case for no reason has disappeared, or will appear.

But in reality, a high risk of failure. During the execution of a transaction in the database, it is possible to encounter a transaction fails, the database system / operating system error, and even the storage medium such as an error. This requires a DBMS transaction fails to perform the restore operation, the database will restore its state to a consistent state (data consistency guaranteed state). In order to achieve the state to restore the database to a consistent state functions, DBMS usually required to maintain a transaction log data to a database to track all transactions affecting operations.

SQL 4 MySQL transaction operations

BEGIN TRANSACTION;
UPDATE t user SET amount = amount-100 WHERE username = 'Java';
UPDATE t user SET amount = amount+ 100 WHERE username = 'Edge';
COMMIT
-- ROLL BACK

So the question is, Java in how does it work?

  • JDBC transaction management process
Connection conn = getConnection();
conn.setAutoCommit(false);
Statement stmt1 = conn. prepareStatement(updateUser1SQL); 
stmt1.executeUpdate();
Statement stmt2 = conn.prepareStatement(updateUser2SQL); 
stmt2.executeUpdate();
conn.commit(); // or conn.rollback (); 事务的提交/回滚

Check out the MySQL transaction isolation level

SELECT @@GLOBAL.tx_ isolation, @@tx_isolation;

reference

发布了373 篇原创文章 · 获赞 483 · 访问量 30万+

Guess you like

Origin blog.csdn.net/qq_33589510/article/details/104871528