python - SQLAlchemy - 使用字典列表更新表

标签 python dictionary sqlalchemy

我有一个包含用户数据的表,我想使用字典列表更新许多用户的信息。目前,我正在使用 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)

提前致谢!

最佳答案

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'}

])

关于python - SQLAlchemy - 使用字典列表更新表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42310430/

相关文章:

python - 在 Heroku 上升级 OpenSSL

python - 将函数输出打印分配给 python 中的变量

python - 在字典列表中附加缺失值

python - 如何使用字典执行多个函数?

python - 将 sqlalchemy 查询结果转换为字典列表

python - 使用 SQLite 在 SQLAlchemy 中返回不同的行

Python/Tkinter : Turn on/off screen updates like wxPython Freeze/Thaw?

java - 确定获得(纬度、经度)对的正确顺序以绘制 N 边的闭合正多边形的方法

python - Dataframe 写入 Postgresql 性能不佳

python - 我需要将所有其他数字乘以 3,但不知道我做错了什么