01 · What is it?
A transaction is a group of database operations treated as one complete unit.
The database commits the unit when every required operation succeeds. If an operation fails, the transaction can roll back the earlier changes.
A transaction groups multiple database operations into one logical unit so they can succeed or fail together.
A transaction is a group of database operations treated as one complete unit.
The database commits the unit when every required operation succeeds. If an operation fails, the transaction can roll back the earlier changes.
Think of moving money between two bank accounts.
One account must be debited and the other must be credited. You do not want only one side to change, so both steps belong to the same all-or-nothing unit.
A transaction helps a database:
Transactions are useful whenever one business action changes more than one piece of data.
BEGIN;
UPDATE accounts
SET balance = balance - 100
WHERE id = 1;
UPDATE accounts
SET balance = balance + 100
WHERE id = 2;
COMMIT;
If either update fails, the application can roll back the transaction so the transfer does not leave the accounts in an incomplete state.
The backend decides which operations belong together and reports whether the unit completed successfully.
A unit that groups related database operations.
One request to read or change database data.
Make a successful transaction permanent.
Undo the changes made by a transaction.
| ENGLISH TERM | 中文 | SIMPLE ENGLISH | 中文小白理解 |
|---|---|---|---|
| Transaction | 事务 | A group of database operations treated as one logical unit. | 把多条数据库操作当成一个整体来执行。 |
| Atomicity | 原子性 | All operations in a transaction succeed together or fail together. | 要么全部成功,要么全部失败,不能只完成一半。 |
| Commit | 提交 | Make the changes in a successful transaction permanent. | 确认这次事务成功,并把改动正式保存下来。 |
| Rollback | 回滚 | Undo changes made during a transaction. | 出错时撤销这次事务已经做过的改动。 |
| Consistency | 一致性 | Keep data valid according to the database rules. | 事务前后都要遵守数据规则,不能留下不合法的数据。 |
| Isolation | 隔离性 | Control how concurrent transactions see each other’s changes. | 多个事务同时运行时,控制它们互相看到哪些改动。 |
| BEGIN | 开始事务 | Start a transaction block. | 告诉数据库,接下来的操作属于同一个事务。 |
| SQL | 结构化查询语言 | A language used to work with relational database data. | 用来查询和修改关系型数据库数据的语言。 |
A transaction groups related database operations into one logical unit.
Commit makes the whole unit permanent; rollback undoes its changes after failure.
Use transactions when a business action must not leave partial data behind.