python - 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()
解决方案
您可以从字典的值创建一个列表并将其用于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)]
推荐阅读
- node.js - 在节点js中部分更新mongodb中嵌套对象数据的最佳方法
- java - Java GWT 应用程序 - 编译有时有效,有时无效
- android - 按住时带有粉红色背景的 RatingBar
- php - 参数必须是数组或对象,在第45行的process.php中实现了Countable,“if(count($result)==1)”有问题
- html - 将选择器转换为 CSS 中的样式
- c# - 将文件写入.NET Core中的临时文件夹后无法读取文件
- javascript - 当我使用 d3.json 访问 json 数据时,图表不再出现
- r - 在 R 中使用大维矩阵进行操作
- seaborn - 在带有图例的 for 循环中使用 Seaborn 绘图
- amazon-web-services - 仅当通过cli不存在时如何创建dynamodb表