There is a simple database with two tables: users and transactions. The users table is used to store user information, and the transactions table is used to store transaction information.
First, create the database and tables:
CREATE DATABASE IF NOT EXISTS my_database;
USE my_database;
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
balance DECIMAL(10, 2) NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS transactions (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
amount DECIMAL(10, 2) NOT NULL,
type ENUM('deposit', 'withdraw') NOT NULL,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Insert some test data:
INSERT INTO users (username, balance) VALUES
('lfsun-1', 1000.00),
('lfsun-2', 500.00),
('lfsun-4', 200.00);
Now, we'll use a transaction to simulate a money transfer operation. Suppose we want to transfer an amount of 100.00 from lfsun-1 to lfsun-2:
-- 开始事务
START TRANSACTION;
-- 更新 lfsun-1 的余额
UPDATE users
SET balance = balance - 100.00
WHERE username = 'lfsun-1';
-- 更新 lfsun-2 的余额
UPDATE users
SET balance = balance + 100.00
WHERE username = 'lfsun-2';
-- 向 transactions 表插入一条记录表示转账操作
INSERT INTO transactions (user_id, amount, type)
VALUES ((SELECT id FROM users WHERE username = 'lfsun-1'), 100.00, 'withdraw'),
((SELECT id FROM users WHERE username = 'lfsun-2'), 100.00, 'deposit');
-- 提交事务
COMMIT;
Now, suppose something went wrong with the transfer and we need to roll back the operation:
-- 开始事务
START TRANSACTION;
-- 更新 lfsun-1 的余额
UPDATE users
SET balance = balance - 100.00
WHERE username = 'lfsun-1';
-- 更新 lfsun-2 的余额
UPDATE users
SET balance = balance + 100.00
WHERE username = 'lfsun-2';
-- 向 transactions 表插入一条记录表示转账操作
INSERT INTO transactions (user_id, amount, type)
VALUES ((SELECT id FROM users WHERE username = 'lfsun-1'), 100.00, 'withdraw'),
((SELECT id FROM users WHERE username = 'lfsun-2'), 100.00, 'deposit');
-- 回滚事务
ROLLBACK;
In some cases, it may be necessary to use savepoints (SAVEPOINT) to achieve finer-grained transaction control:
-- 开始事务
START TRANSACTION;
-- 更新 lfsun-1的余额
UPDATE users SET balance = balance - 100.00 WHERE username = 'lfsun-1';
-- 保存点1
SAVEPOINT point1;
-- 更新 lfsun-2 的余额
UPDATE users SET balance = balance + 100.00 WHERE username = 'lfsun-2';
-- 向 transactions 表插入一条记录表示转账操作
INSERT INTO transactions (user_id, amount, type) VALUES
((SELECT id FROM users WHERE username = 'lfsun-1'), 100.00, 'withdraw'),
((SELECT id FROM users WHERE username = 'lfsun-2'), 100.00, 'deposit');
-- 发生错误,回滚到保存点1
ROLLBACK TO point1;
-- 提交事务
COMMIT;
Finally, demonstrate the use of table locks (LOCK TABLES and UNLOCK TABLES):
-- 锁定 users 表,防止其他会话对其进行修改
LOCK TABLES users WRITE;
-- 执行一些操作,例如更新或插入数据
-- 解锁 users 表
UNLOCK TABLES;