久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

Python Sqlalchemy如何實(shí)現(xiàn)select for update

瀏覽:49日期:2022-07-08 15:36:14

sqlalchemy 對(duì)于行級(jí)鎖有兩種實(shí)現(xiàn)方式,with_lockmode(self, mode): 和 with_for_update(self, read=False, nowait=False, of=None),前者在sqlalchemy 0.9.0 被廢棄,用后者代替。所以我們使用with_for_update !

看下函數(shù)的定義:

@_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 是標(biāo)識(shí)加互斥鎖還是共享鎖. 當(dāng)為 True 時(shí), 即 for share 的語(yǔ)句, 是共享鎖. 多個(gè)事務(wù)可以獲取共享鎖, 互斥鎖只能一個(gè)事務(wù)獲取. 有'多個(gè)地方'都希望是'這段時(shí)間我獲取的數(shù)據(jù)不能被修改, 我也不會(huì)改', 那么只能使用共享鎖.nowait 其它事務(wù)碰到鎖, 是否不等待直接'報(bào)錯(cuò)'.of 指明上鎖的表, 如果不指明, 則查詢中涉及的所有表(行)都會(huì)加鎖.

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

對(duì)應(yīng)于sql:

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

Python Sqlalchemy如何實(shí)現(xiàn)select for update

mysql 不支持這幾個(gè)參數(shù),轉(zhuǎn)成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())

結(jié)果:

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 的用法,不過(guò)鎖定(Lock)的數(shù)據(jù)是判別就得要注意一下了。由于InnoDB 預(yù)設(shè)是Row-Level Lock,所以只有「明確」的指定主鍵,MySQL 才會(huì)執(zhí)行Row lock (只鎖住被選取的數(shù)據(jù)) ,否則mysql 將會(huì)執(zhí)行Table Lock (將整個(gè)數(shù)據(jù)表單給鎖住)。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 商洛市| 长汀县| 稻城县| 河津市| 合作市| 高淳县| 治县。| 牡丹江市| 吉水县| 丰台区| 高安市| 莱西市| 兖州市| 六安市| 汶上县| 浦江县| 凤山市| 九江县| 贵德县| 汶川县| 仁布县| 汉沽区| 福贡县| 措美县| 新源县| 婺源县| 南丰县| 邻水| 焦作市| 时尚| 开远市| 东明县| 桑植县| 南雄市| 连南| 华容县| 麦盖提县| 江陵县| 六枝特区| 红安县| 修文县|