Python SQLAlchemy-使用字典列表更新表
我有一个包含用户数据的表,我想使用字典列表更新许多用户的信息。目前,我正在使用for循环一次发送一个update语句,一个dictionary,但是速度很慢,我希望有一种批量方法来实现这一点Python SQLAlchemy-使用字典列表更新表,python,dictionary,sqlalchemy,Python,Dictionary,Sqlalchemy,我有一个包含用户数据的表,我想使用字典列表更新许多用户的信息。目前,我正在使用for循环一次发送一个update语句,一个dictionary,但是速度很慢,我希望有一种批量方法来实现这一点 user_data = [{'user_id' : '12345', 'user_name' : 'John'}, {'user_id' : '11223', 'user_name' : 'Andy'}] connection = engine.connect() metadata = MetaDa
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)
提前谢谢 希望这会有帮助!谢谢在本例中,我是否应该在where语句中将“id”更改为“user\u id”,将“\u id”更改为“user\u id”?所以它应该是:
where(users\u table.c.user\u id==bindparam('user\u id'))。
否则我会得到:StatementError:(sqlalchemy.exc.InvalidRequestError)bind参数'\u id
@Venetian需要一个值,这取决于您使用的数据库,可能不会显著提高性能。例如,看看(PostgreSQL)。
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'}
])