简体   繁体   中英

SQLAlchemy update neither works nor raises errors

I want to update the email column of the user table where id == 3 . Below code does not update any rows or even raise any errors. Where could the problem be?

from sqlalchemy import update
@app.route('/testupdate/')
def testupdate():
    stmt = update(user).where(user.id==3).values(email='a@b')
    db.session.commit()
    return 'done'

The problem is that no SQL was emitted to the database.

    stmt = update(user).where(user.id==3).values(email='a@b')

Does not actually execute the statement, it just creates it. To actually execute it you have to pass it to

    db.session.execute(stmt)

and then commit. You could also instead just use the Query API of the session:

    db.session.query(user).\
        filter_by(id=3).\
        update({user.email: 'a@b'},
               synchronize_session='evaluate')

Note that depending on whether or not you have the affected instances in the session and will be using them later on you could choose not to synchronize at all with False .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM