mysql_5.5.8_教程_09 事务transaction 与 锁定lock

2011-03-18  分类:mysql_5.5.8 标签:  作者:fanzg



这是有声音的视频,请检查播放器或者声音输出设备。

这次的学习内容: 事务transaction 与 锁定lock

==============================

create database yin_hang character set utf8 collate utf8_general_ci;

use yin_hang;

create table zhang_hao(
id int(20) auto_increment not null primary key,
xing_ming varchar(50) not null,
jin_e int
);

insert into zhang_hao(xing_ming,jin_e) values('张三',100),('李四',100);

=============================
事务的出现, 考虑这样的一个经典例子:

张三账户转账100元到李四的账户

1,张三账户减去100元
2,李四账户增加100元

====================
默认自动提交
mysql> select @@autocommit;
+--------------+
| @@autocommit |
+--------------+
|            1 |
+--------------+
1 row in set (0.00 sec)

mysql> set @@autocommit=0;
Query OK, 0 rows affected (0.00 sec)

mysql> select @@autocommit;
+--------------+
| @@autocommit |
+--------------+
|            0 |
+--------------+

start transaction;
update zhang_hao set jin_e=0 where xing_ming='张三';
rollback;
commit;

===================
回滚到自定义点
start transaction;
update zhang_hao set jin_e=0 where xing_ming='张三';
update zhang_hao set jin_e=200 where xing_ming='李四';
savepoint s1;
update zhang_hao set jin_e=250 where xing_ming='李四';
rollback to s1;
commit;

=================================================
锁定 lock

数据库有一个特性, 允许多用户访问, 就会出现 并发性。

例如, 网上购物系统, 只剩下一本书, 张三,李四 同时进行网上购买剩下这本书

有可能他们都会买到这本书, 但是不符合现实,因为只有一本书

这样我们通过锁来实现 (read, write)

mysql> lock tables zhang_hao read;

mysql> select * from zhang_hao;

由于对账号表进行了读权限进行锁定,所以更新失败

mysql> update zhang_hao set jin_e=1000 where xing_ming='张三';

ERROR 1099 (HY000): Table 'zhang_hao' was locked with a READ lock and can't be updated

mysql> unlock tables;

解开锁之后,成功更新
mysql> update zhang_hao set jin_e=1000 where xing_ming='张三';

Query OK, 0 rows affected (0.00 sec)
Rows matched: 1  Changed: 0  Warnings: 0

视频演示到这里, 88


“mysql_5.5.8_教程_09 事务transaction 与 锁定lock”有1个评论

  1. 03月 21st, 2011 at 12:25:42 #如何化妆

    兔年吉祥~

    [回复]

有任何疑问或建议,可以给作者留言:



公告:

  • 2010年5月之前的视频是文字解说演示,没有声音。
  • 2010年5月以后的视频全部带声音。