关系型数据库通过sql语句实现悲观锁与乐观锁
pgsql建表语句(MySql同理):
-- public.newtable definition-- Drop table-- DROP TABLE public.newtable;CREATE TABLE public.newtable (id varchar NULL,"name" varchar NULL,count int4 NULL,t_version int4 NULL
);
悲观锁:
----关系型数据库实现悲观锁(select for update)----开启事务
begin;
----锁定目标行(其他事务尝试锁定同一行会被阻塞;id:目标id)
select id,name,count,t_version from newtable where id='1' for update ;
----执行更新操作(锁定期间保证数据独占)
update newtable set count =count-1 where id='1';
----提交事务(释放锁)
commit;
乐观锁:
----关系型数据库实现乐观锁(使用version版本号字段控制,and t_version=1这里的版本号是当前事务之前最近查询到的版本号)
----获取最新版数据
select id,name,count,t_version from newtable where id='1';
----开启事务
begin;
update newtable set count=count-1,t_version =t_version +1 where id='1' and t_version=1;
----提交事务(释放锁)
commit;