推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
whx20202
V2EX  ›  Python

请问一下 sqlalchemy 在乐观锁的时候,怎么知道自己更新了几行或者是否更新成功?

  •  
  •   whx20202 · Dec 26, 2018 · 3768 views
    This topic created in 2740 days ago, the information mentioned may be changed or developed.

    我理解 sqlalchemy 在事务中,update 不会立刻生效,甚至不会立刻发到服务器上,而是等到 commit 才生效。

    举个例子:

    with Seesion as session:
        object = session.query(Table).where(key=param).limit(1)
    
        content = "这里是业务逻辑计算的值"
    
        # 用取到的对象的 ID 进行更新,只有一个线程能更新成功,我理解
        Table.update(Table).set(Table.content = content).where(id = object.id)
        sessoin.commit()
    

    那么问题来了,如果我想知道我 update 操作(或者说是 commit 操作)是否成功(影响了一行)该怎么办呢? 因为可能还有一些后续操作,需要确认更新成功,拿到锁才能继续

    6 replies    2019-01-03 17:19:14 +08:00
    gamexg
        1
    gamexg  
       Dec 26, 2018 via Android
    很长时间没用 python 了,
    update 返回值应该是实际更新的函数。
    SleipniR
        2
    SleipniR  
       Dec 27, 2018
    如果 update 或 commit 不成功,会直接抛出异常吧。
    拿到锁才能继续是什么意思?
    keakon
        3
    keakon  
       Dec 27, 2018
    1. 你这没有乐观锁
    2. update 没在事务中
    3. ResultProxy.rowcount 是更新的行数
    lolizeppelin
        4
    lolizeppelin  
       Dec 27, 2018
    query= session.query(Table).where(key=param).limit(1)
    with session.begin():
    ____query.update({key: value})
    ____session.commt()

    这样写才是事务
    15399905591
        5
    15399905591  
       Dec 27, 2018
    你的问题没描述清楚,你是需要加锁操作,每次只能有一个对象能够更新 Table ?
    whx20202
        6
    whx20202  
    OP
       Jan 3, 2019
    @keakon #3 感谢。
    第二点确实是我写范例代码时候疏忽了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2789 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 04:29 · PVG 12:29 · LAX 21:29 · JFK 00:29
    ♥ Do have faith in what you're doing.