首页 > 解决方案 > python将字典值保存到数据库

问题描述

我有一个像下面这样的 Python 字典和一本书籍字典

[{'title': 'Game of Thrones', 'summary': 'summary detail', 'number': 4},
{'title': 'James and the Giant Peach', 'summary': 'summary detail', 'number': 1}]

我想遍历字典并将值保存到 mysql DB,最好的方法是什么?请有任何建议

books.items() //this is the Python book dict


//set up DB connection
db = mysql.connector.connect()
cursor = db.cursor()


sql = "INSERT INTO BOOKS (title, summary, number) VALUES (%s,%s,%s)"
val = ("Title1", "Summary", "Number3") 

cursor.execute(sql, val)
db.commit()

标签: pythonsqldatabasedictionary

解决方案


您可以从字典的值创建一个列表并将其用于executemany

sql = "INSERT INTO BOOKS (title, summary, number) VALUES (%s,%s,%s)"
values = [tuple(d.values()) for d in books]

cursor.executemany(sql, values)

values列表如下所示:

[('Game of Thrones', 'summary detail', 4), ('James and the Giant Peach', 'summary detail', 1)]

推荐阅读