简体   繁体   中英

Insert or update using a dictionary

I'm trying to update values using a dictionary. My user_id is set. I want to update date_synced where user_id=user_id . User table looks like this: User(user_id, mail, active, activity_level, date_synced) .

Dictionary dictUsers looks like:

[{'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. 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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