本文只介绍基础、常用的 MySQL 语法语句,更详细的语法语句请移步这里。
另本文所使用的数据库及对应的表请参考MySQL数据定义语句。
1 START TRANSACTION, COMMIT和ROLLBACK 语法
语法
START TRANSACTION | BEGIN [WORK]
COMMIT [WORK] [AND [NO] CHAIN] [[NO] RELEASE]
ROLLBACK [WORK] [AND [NO] CHAIN] [[NO] RELEASE]
SET AUTOCOMMIT = {0 | 1}
1.1 事务例子
BEGIN;
INSERT INTO SC VALUES(201215122, 4, 78);
COMMIT;
查看一下有没有插入数据成功
BEGIN;
INSERT INTO SC VALUES(201215125, 4, 85);
ROLLBACK;
查看一下数据
2 SAVEPOINT和ROLLBACK TO SAVEPOINT 语法
语法
SAVEPOINT identifier
ROLLBACK [WORK] TO SAVEPOINT identifier
RELEASE SAVEPOINT identifier
2.1 示例
BEGIN;
UPDATE SC
SET Grade=82
WHERE Sno = 201215122
AND Cno = 4;
SAVEPOINT point1;
INSERT INTO SC VALUES(201215125, 4, 69);
SAVEPOINT point2;
ROLLBACK TO point1;
3 LOCK TABLES和UNLOCK TABLES 语法
语法
LOCK TABLES
tbl_name [AS alias] {READ [LOCAL] | [LOW_PRIORITY] WRITE}
[, tbl_name [AS alias] {READ [LOCAL] | [LOW_PRIORITY] WRITE}] ...
UNLOCK TABLES
3.1 示例
LOCK TABLE SC;
打开另一个会话尝试更新 SC
表的数据
发现会阻塞在这里。尝试在新会话中给 SC
表加写锁
同样也会阻塞在这里。尝试在新会话中查询
查询成功,尝试给 SC
表加读锁
同样成功上锁。UNLOCK TABLES
释放被当前会话持有的任何锁
UNLOCK TABLES;
参考
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/275692.html