PostgreSQL Tutorial: ACID Characteristics and Basic Use of Transactions

What is ACID?

In daily operations, for a set of related operations, it is usually required that either all succeed or all fail. In a relational database, this set of operations is called a transaction. In order to ensure the security of the overall transaction, there is ACID:

  • Atomicity A: A transaction is the smallest execution unit. All operations in a transaction either succeed or fail.
  • Consistency C: All data must remain in a consistent state when the transaction is completed. (After the transaction is completed, the final result is consistent with the expected result)
  • Isolation: A transaction operation is either the state before other transaction operations or the state after other transaction operations. There is no intermediate state.
  • Durability: After the transaction is committed, the data will be dropped to the local disk, and the modifications will be permanent.

In PostgreSQL, transaction concurrency issues are also based on MVCC and multi-version concurrency control to maintain data consistency. Compared with traditional lock operations, the biggest advantage of MVCC is that it can prevent reading and writing from conflicting with each other .

Of course, PostgreSQL also supports table locks and row locks, which can solve write-write conflicts.

Compared with other data, PostgreSQL has a relatively large optimization, DDL can also be included in a transaction. For example, for operations in a cluster, a transaction can only be considered successful if it can ensure that multiple nodes build a table.

Basic usage of transactions

First of all, based on the previous operations, you should have realized that PostgreSQL automatically commits transactions. It is the same as MySQL.

This can be done based on turning off PostgreSQL's autocommit transactions.

image.png

But the above method is more troublesome than the traditional method.

Just three commands:

  • begin: start transaction
  • commit: commit transaction
  • rollback: rollback transaction
-- 开启事务
begin;
-- 操作
insert into test values (7,'bbb',12,5);
-- 提交事务 
commit;

Guess you like

Origin blog.csdn.net/a772304419/article/details/132928921