简体   繁体   English

使用字典插入或更新

[英]Insert or update using a dictionary

I'm trying to update values using a dictionary. 我正在尝试使用字典更新值。 My user_id is set. 我的user_id已设置。 I want to update date_synced where user_id=user_id . 我想update date_synced where user_id=user_id User table looks like this: User(user_id, mail, active, activity_level, date_synced) . 用户表如下所示: User(user_id, mail, active, activity_level, date_synced)

Dictionary dictUsers looks like: 字典dictUsers看起来像:

[{'user_id': 1, 'date_synced': '2019-05-22 10:42:25'},
 {'user_id': 8, 'date_synced': '2019-05-22 10:42:25'}]

What I've tried: 我尝试过的:

sql = 'UPDATE User SET {}'.format(', '.join('{}'.format(k) for k in dictUsers))
conn.execute(sql, dictUsers.values())

My error: 我的错误:

AttributeError: 'list' object has no attribute 'values'

Expected output is date_synced updated in my User table. 预期的输出是在我的用户表中更新的date_synced。 How can I do this? 我怎样才能做到这一点?

Try something like this (from the official documentation ): 尝试这样的东西(来自官方文档 ):

stmt = users.update().\
        values(name='ed wood').\
        where(users.c.id == addresses.c.id)
conn.execute(stmt)

In your case this should be something like this. 在你的情况下,这应该是这样的。 You can loop this over your dictionary to do for every user: 你可以在你的字典上循环这个为每个用户做:

stmt = user.update().\
        values(date_synced=dictUsers[i].date_synced).\
        where(user.c.user_id == dictUsers[i].user_id)
conn.execute(stmt)

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

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