python - 如何使用python在mysql中插入python dict的键和值

标签 python mysql dictionary insert executemany

我有一个像这样的Python字典:

my_dict = {'find': ['http://time.com', 'http://find.com'], 'time': ['http://any.com', 'http://www.tim.com', 'http://mine.in']...}

我想在 mysql 表的两个不同列中插入字典 my_dict。列名称分别为 termurls。我现在有三列:idtermurls我想将每个键和值对插入不同的行中。

我想将链接存储在 urls 中,并以逗号分隔。 my_dict 值中的网站链接必须以逗号分隔存储,例如 http://time.com, http://mine.com. 我尝试按以下方式插入

for i in my_dict.items():   
    keys = i[0]
    values = i[1]
    sql = """INSERT INTO index_table (term, urls) VALUES (%s, %s)"""
    cursor.execute(sql, (keys, values))

但它显示以下错误:

(1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '))' at line 1")

最佳答案

此实例中的值是您尝试传递给 SQL 查询的列表,这会导致出现问题。

如果您希望值部分中的每个网址都有一个单独的记录(假设您始终有一个值部分的列表)

for i in my_dict.items():
    term = i[0]
    for url in i[1]:
        sql = """INSERT INTO index_table (term, urls) VALUES (%s, %s)"""
        cursor.execute(sql, (term, url))

或者,如果您想将 url 一起存储在一条记录中,则需要 pickle 列表或转换为 json 等格式。从数据库中提取数据时需要适本地处理数据

import json
for i in my_dict.items():
    term = i[0]
    urls = json.dumps(i[1])
    sql = """INSERT INTO index_table (term, urls) VALUES (%s, %s)"""
    cursor.execute(sql, (term, urls))

以逗号分隔格式存储网址;

for i in my_dict.items():
    term = i[0]
    urls = ', '.join(i[1])
    sql = """INSERT INTO index_table (term, urls) VALUES (%s, %s)"""
    cursor.execute(sql, (term, urls))

关于python - 如何使用python在mysql中插入python dict的键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12295605/

相关文章:

python - 在 PySide2 中为 QML 注册枚举

mysql - 在子查询中引用查询结果别名

Python 列表分组和求和

java - HashMap中put()的返回值

LINQ 将字典转换为查找

python - osetests 覆盖率报告跳过了一些 .py 文件,但不确定原因

python - 使用 C 扩展 Python 错误 : Segmentation Fault: 11 in Python [MacOS X]

python - 如何用Qt设计倒计时

c# - 系统找不到iis服务器中指定的文件

php - 如何让用户以表单形式提交文本并使用 AJAX 将其输入到数据库并显示在同一页面上?