使用WHERE在SQLAlchemy Core中进行批量更新 [英] Bulk update in SQLAlchemy Core using WHERE

查看:797
本文介绍了使用WHERE在SQLAlchemy Core中进行批量更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经设法在SQLAlchemy中使用批量插入,例如:

I have managed to work with the bulk insert in SQLAlchemy like:

conn.execute(addresses.insert(), [ 
   {'user_id': 1, 'email_address' : 'jack@yahoo.com'},
   {'user_id': 1, 'email_address' : 'jack@msn.com'},
   {'user_id': 2, 'email_address' : 'www@www.org'},
   {'user_id': 2, 'email_address' : 'wendy@aol.com'},
])

我现在需要的是等同于更新的东西.我已经尝试过了:

What I need now is something equivalent for update. I have tried this:

conn.execute(addresses.insert(), [ 
   {'user_id': 1, 'email_address' : 'jack@yahoo.com', 'id':12},
   {'user_id': 1, 'email_address' : 'jack@msn.com', 'id':13},
   {'user_id': 2, 'email_address' : 'www@www.org', 'id':14},
   {'user_id': 2, 'email_address' : 'wendy@aol.com', 'id':15},
])

期望每一行都会根据'id'字段进行更新,但是这行不通.我以为是因为我没有指定WHERE子句,但是我不知道如何使用字典中包含的数据指定WHERE子句.

expecting that each row gets updated according to the 'id' field, but it doesn't work. I assume that it is because I have not specified a WHERE clause, but I don't know how to specify a WHERE clause using data that is included in the dictionary.

有人可以帮我吗?

推荐答案

阅读

Read Inserts, Updates and Deletes section of the documentation. Following code should get you started:

from sqlalchemy.sql.expression import bindparam
stmt = addresses.update().\
    where(addresses.c.id == bindparam('_id')).\
    values({
        'user_id': bindparam('user_id'),
        'email_address': bindparam('email_address'),
    })

conn.execute(stmt, [
    {'user_id': 1, 'email_address' : 'jack@yahoo.com', '_id':1},
    {'user_id': 1, 'email_address' : 'jack@msn.com', '_id':2},
    {'user_id': 2, 'email_address' : 'www@www.org', '_id':3},
    {'user_id': 2, 'email_address' : 'wendy@aol.com', '_id':4},
])

这篇关于使用WHERE在SQLAlchemy Core中进行批量更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆