时间:2021-05-22
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
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 (将整个数据表单给锁住)。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
一、SQLAlchemy简介1.1、SQLAlchemy是什么?sqlalchemy是一个python语言实现的的针对关系型数据库的orm库。可用于连接大多数常
python之sqlalchemy创建表的实例详解通过sqlalchemy创建表需要三要素:引擎,基类,元素fromsqlalchemyimportcreate
本文实例讲述了Python流行ORM框架sqlalchemy安装与使用。分享给大家供大家参考,具体如下:安装http://docs.sqlalchemy.org
一、SQLalchemy简介SQLAlchemy是一个开源的SQL工具包,基本Python编程语言的MIT许可证而发布的对象关系映射器。SQLAlchemy提供
EXPLAIN语句提供有关MySQL如何执行语句的信息。EXPLAIN与SELECT,DELETE,INSERT,REPLACE和UPDATE语句一起使用。EX