MySQL行锁深入研究
来源:http://blog.csdn.net/ldb2741/archive/2010/02/25/5325161.aspx
做项目时由于业务逻辑的需要,必须对数据表的一行或多行加入行锁,举个最简单的例子,图书借阅系统。假设 id=1 的这本书库存为 1 ,但是有 2 个人同时来借这本书,此处的逻辑为
view plaincopy to clipboardprint?
Select restnum from book where id =1 ;
-- 如果 restnum 大于 0 ,执行 update
Update book set restnum=restnum-1 where id=1 ;
Select restnum from book where id =1 ;
-- 如果 restnum 大于 0 ,执行 update
Update book set restnum=restnum-1 where id=1 ;
问题就来了,当 2 个人同时来借的时候,有可能第一个人执行 select 语句的时候,第二个人插了进来,在第一个人没来得及更新 book 表的时候,第二个人查到数据了,其实是脏数据,因为第一个人会把 restnum 值减 1 ,因此第二个人本来应该是查到 id=1 的书 restnum 为 0 了,因此不会执行 update ,而会告诉它 id=1 的书没有库存 了,可是数据库哪懂这些,数据库只负责执行一条条 SQL 语句,它才不管中间有没有其他 sql 语句插进来,它也不知道要把一个 session 的 sql 语句执行完再执行另一个 session 的。因此会导致并发的时候 restnum 最后的结果为 -1 ,显然这是不合理的,所以,才出现锁的概念, Mysql 使用 innodb 引擎可以通过索引 对数据行加锁。以上借书的语句变为:
view plaincopy to clipboardprint?
Begin;
Select restnum from book where id =1 for update ;
-- 给 id=1 的行加上排它锁且 id 有索引
Update book set restnum=restnum-1 where id=1 ;
Commit;
Begin;
Select restnum from book where id =1 for update ;
-- 给 id=1 的行加上排它锁且 id 有索引
Update book set restnum=restnum-1 where id=1 ;
Commit;
这样,第二个人执行到 select 语句的时候就会处于等待状态直到第一个人执行 commit
相关文档:
具有负载均衡功能MySQL服务器集群部署实现
http://www.realure.cn/2009_241.html
http://www.realure.cn/2009_242.html
http://www.realure.cn/2009_243.html
http://www.realure.cn/2009_244.html
http://www.realure.cn/2009_245.html ......
导入数据指定列
load data local infile 'D:\\service_func_utf8.txt' into table service_func fields terminated by '\t' (service_id, func_id1, func_id2, func_id3, func_id4, func_id5, func_id6);
MYSQL将查询结果导出到文件
select * from tablename into outfile '/tmp/test.txt';
MYSQL联合主键
create  ......
PHP 存取 MySQL 乱码问题
上一篇 / 下一篇 2007-06-04 03:33:50 / 个人分类:PHP学习
查看( 239 ) / 评论( 0 ) / 评分( 0 / 0 )
MySQL 的字符集支持(Character Set Support)有两个方面:字符集(Character set)和排序方式(Collation)。对于字符集的支持细化到四个层次: 服务器(server),数据库(database),数据表 ......
配置MySQL主从复制(Replication)
标签:知识/探索 mysql复制 replication mysql备份
分类:数据库
MySQL支持单向、异步复制,复制过程中一个服务器充当主服务器,而一个或多个其它服务器充当从服务器。主服务器将更新写入二进制日志文件,并维护日志文件的一个索引以跟踪日志循环。当一个从服务 ......
导出.sql文件
1.将数据库transfer_server_db导出到transfSRV.sql文件中:
mysqldump -u root -p transfer_server_db > /home/eric/transfSRV.sql
2.将数据库transfer_server_db中的device_info_table导出到table.sql文件中:
mysqldump -u root -p transfer_server_db device_info_table > /home/eric/ta ......