我有一个像这样的Python字典:
my_dict = {'find': ['http://time.com', 'http://find.com'], 'time': ['http://any.com', 'http://www.tim.com', 'http://mine.in']...}
我想在 mysql 表的两个不同列中插入字典 my_dict
的键
和值
。列名称分别为 term
和 urls
。我现在有三列:id
、term
、urls
和我想将每个键和值对插入不同的行中。
我想将链接存储在 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/