首页 > 解决方案 > 蟒蛇 MySQL。如何从字典中插入重复键更新

问题描述

我正在从 Python 字典更新 MySQL 数据库表,其中键是数据库字段。我有一个有效的插入语句,但我真正需要的是 INSERT ON DUPLICATE KEY UPDATE。这是插入语句:

for d in r.json()['mydict'].items():  
    d = d[1] #the dictionary is the 2nd element in the tuple
    placeholders = ', '.join(['%s'] * len(d))
    columns = ', '.join(d.keys())
    sql = "INSERT INTO %s ( %s ) VALUES ( %s )" % ("my_table", columns, placeholders) 
    c = create_connection() #from function create tables
    cur = c[0] #function returns cursor
    db = c[1] #function returns db
    cur.execute(sql, list(d.values()))
    db.commit()
    db.close()

一如既往,任何帮助表示赞赏。

标签: pythonmysqldictionary

解决方案


推荐阅读