Python Sqlalchemy如何实现select for update


Posted in Python onOctober 12, 2020

sqlalchemy 对于行级锁有两种实现方式,with_lockmode(self, mode): 和 with_for_update(self, read=False, nowait=False, of=None),前者在sqlalchemy 0.9.0 被废弃,用后者代替。所以我们使用with_for_update !

看下函数的定义:

@_generative()
  def with_for_update(self, read=False, nowait=False, of=None):
    """return a new :class:`.Query` with the specified options for the
    ``FOR UPDATE`` clause.
 
    The behavior of this method is identical to that of
    :meth:`.SelectBase.with_for_update`. When called with no arguments,
    the resulting ``SELECT`` statement will have a ``FOR UPDATE`` clause
    appended. When additional arguments are specified, backend-specific
    options such as ``FOR UPDATE NOWAIT`` or ``LOCK IN SHARE MODE``
    can take effect.
 
    E.g.::
 
      q = sess.query(User).with_for_update(nowait=True, of=User)
 
    The above query on a Postgresql backend will render like::
 
      SELECT users.id AS users_id FROM users FOR UPDATE OF users NOWAIT
 
    .. versionadded:: 0.9.0 :meth:`.Query.with_for_update` supersedes
      the :meth:`.Query.with_lockmode` method.
 
    .. seealso::
 
      :meth:`.GenerativeSelect.with_for_update` - Core level method with
      full argument and behavioral description.
 
    """
     
read
  是标识加互斥锁还是共享锁. 当为 True 时, 即 for share 的语句, 是共享锁. 多个事务可以获取共享锁, 互斥锁只能一个事务获取. 有"多个地方"都希望是"这段时间我获取的数据不能被修改, 我也不会改", 那么只能使用共享锁.
nowait
  其它事务碰到锁, 是否不等待直接"报错".
of
  指明上锁的表, 如果不指明, 则查询中涉及的所有表(行)都会加锁.

q = sess.query(User).with_for_update(nowait=True, of=User)

对应于sql:

SELECT users.id AS users_id FROM users FOR UPDATE OF users NOWAIT

Python Sqlalchemy如何实现select for update

mysql 不支持这几个参数,转成sql都是:

SELECT users.id AS users_id FROM users FOR UPDATE

范例:

def query_city_for_update():
  session = get_session()
  with session.begin():
    query = session.query(City).with_for_update().filter(City.ID == 8)
    print 'SQL : %s' % str(query)
    print_city_info(query.first())

结果:

SQL : SELECT city."ID" AS "city_ID", city."Name" AS "city_Name", city."CountryCode" AS "city_CountryCode", city."District" AS "city_District", city."Population" AS "city_Population" 
FROM city 
WHERE city."ID" = :ID_1 FOR UPDATE

{'city': {'population': 234323, 'district': u'Utrecht', 'id': 8, 'country_code': u'NLD', 'name': u'Utrecht'}}

SELECT ... FOR UPDATE 的用法,不过锁定(Lock)的数据是判别就得要注意一下了。由于InnoDB 预设是Row-Level Lock,所以只有「明确」的指定主键,MySQL 才会执行Row lock (只锁住被选取的数据) ,否则mysql 将会执行Table Lock (将整个数据表单给锁住)。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python定时检查某个进程是否已经关闭的方法
May 20 Python
python实现批量下载新浪博客的方法
Jun 15 Python
python3.5使用tkinter制作记事本
Jun 20 Python
轻松掌握python设计模式之访问者模式
Nov 18 Python
python 线程的暂停, 恢复, 退出详解及实例
Dec 06 Python
Python实例方法、类方法、静态方法的区别与作用详解
Mar 25 Python
解决Python正则表达式匹配反斜杠''\''问题
Jul 17 Python
基于django传递数据到后端的例子
Aug 16 Python
Pytorch实现基于CharRNN的文本分类与生成示例
Jan 08 Python
Python sklearn中的.fit与.predict的用法说明
Jun 28 Python
Python collections模块的使用方法
Oct 09 Python
Python图像处理之膨胀与腐蚀的操作
Feb 07 Python
浅析PyCharm 的初始设置(知道)
Oct 12 #Python
Pandas替换及部分替换(replace)实现流程详解
Oct 12 #Python
Django windows使用Apache实现部署流程解析
Oct 12 #Python
详解Django ORM引发的数据库N+1性能问题
Oct 12 #Python
如何实现一个python函数装饰器(Decorator)
Oct 12 #Python
Vs Code中8个好用的python 扩展插件
Oct 12 #Python
Django中和时区相关的安全问题详解
Oct 12 #Python
You might like
海河写的 Discuz论坛帖子调用js的php代码
2007/08/23 PHP
PHP 防恶意刷新实现代码
2010/05/16 PHP
Views rows style模板重写代码
2011/05/16 PHP
Symfony2针对输入时间进行查询的方法分析
2017/06/28 PHP
详解Laravel5.6 Passport实现Api接口认证
2018/07/27 PHP
元素的内联事件处理函数的特殊作用域在各浏览器中存在差异
2011/01/12 Javascript
js中更短的 Array 类型转换
2011/10/30 Javascript
Ionic2系列之使用DeepLinker实现指定页面URL
2016/11/21 Javascript
VUE2.0中Jsonp的使用方法
2018/05/22 Javascript
记React connect的几种写法(小结)
2018/09/18 Javascript
vue组件中的样式属性scoped实例详解
2018/10/30 Javascript
Python中使用Boolean操作符做真值测试实例
2015/01/30 Python
python smtplib模块发送SSL/TLS安全邮件实例
2015/04/08 Python
总结网络IO模型与select模型的Python实例讲解
2016/06/27 Python
python实现kNN算法
2017/12/20 Python
unittest+coverage单元测试代码覆盖操作实例详解
2018/04/04 Python
python将秒数转化为时间格式的实例
2018/09/16 Python
Python拼接字符串的7种方法总结
2018/11/01 Python
python重试装饰器的简单实现方法
2019/01/31 Python
Django框架设置cookies与获取cookies操作详解
2019/05/27 Python
python实现微信小程序用户登录、模板推送
2019/08/28 Python
在python3中实现更新界面
2020/02/21 Python
python实现小程序推送页面收录脚本
2020/04/20 Python
keras:model.compile损失函数的用法
2020/07/01 Python
SheIn俄罗斯:时尚女装网上商店
2017/02/28 全球购物
美国快时尚彩妆品牌:Winky Lux(透明花瓣润唇膏)
2018/11/06 全球购物
新东网科技Java笔试题
2012/07/13 面试题
土木工程个人自荐信范文
2013/11/30 职场文书
品牌推广策划方案
2014/05/28 职场文书
红色旅游心得体会
2014/09/03 职场文书
会议开幕词
2015/01/28 职场文书
2015年小学校长工作总结
2015/05/19 职场文书
学历证明范文
2015/06/16 职场文书
幼儿园安全教育随笔
2015/08/14 职场文书
股东出资协议书
2016/03/21 职场文书
Django给表单添加honeypot验证增加安全性
2021/05/06 Python