简体   繁体   English

SQLAlchemy-使用字典列表更新表

[英]SQLAlchemy - Update table using list of dictionaries

I have a table containing user data and I would like to update information for many of the users using a list of dictionaries. 我有一个包含用户数据的表,我想使用词典列表来更新许多用户的信息。 At the moment I am using a for loop to send an update statement one dictionary at a time, but it is slow and I am hoping that there is a bulk method to do this. 目前,我正在使用for循环来一次向一个字典发送更新语句,但这很慢,我希望有一个批量方法可以做到这一点。

user_data = [{'user_id' : '12345', 'user_name' : 'John'}, {'user_id' : '11223', 'user_name' : 'Andy'}]   

connection = engine.connect()
metadata = MetaData()

for row in user_data:
        stmt = update(users_table).where(users_table.columns.user_id == row['user_id'])
        results = connection.execute(stmt, row)

Thanks in advance! 提前致谢!

from sqlalchemy.sql.expression import bindparam

connection = engine.connect()

stmt = users_table.update().\
where(users_table.c.id == bindparam('_id')).\
values({
    'user_id': bindparam('user_id'),
    'user_name': bindparam('user_name'),
})

connection.execute(stmt, [
{'user_id' : '12345', 'user_name' : 'John', '_id': '12345'},
{'user_id' : '11223', 'user_name' : 'Andy', '_id': '11223'}

])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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