国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

Python Sqlalchemy如何實現select for update

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

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 編程
相關文章:
主站蜘蛛池模板: 利川市| 德州市| 陆良县| 德惠市| 宜君县| 嵊州市| 始兴县| 色达县| 普兰县| 昭觉县| 洛川县| 伊宁市| 罗定市| 崇义县| 宜兴市| 武功县| 富锦市| 洞口县| 通渭县| 天全县| 东丽区| 辽中县| 蕲春县| 惠来县| 新和县| 丘北县| 景谷| 蒙自县| 会泽县| 台州市| 西乌珠穆沁旗| 赞皇县| 上林县| 白沙| 来安县| 罗江县| 鞍山市| 阿鲁科尔沁旗| 皮山县| 清水河县| 汝南县|