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

如何使用python在mysql中插入python dict的键和值,python,mysql,dictionary,insert,executemany,Python,Mysql,Dictionary,Insert,Executemany,我有一个类似这样的python dict: my_dict = {'find': ['http://time.com', 'http://find.com'], 'time': ['http://any.com', 'http://www.tim.com', 'http://mine.in']...} 我想在mysql表的两个不同列中插入dictionarymy_dict的键和值。列名称分别是term和url。我现在有三列:id、term、url和我想在不同的行中插入每个键和值对。 我想将链接

我有一个类似这样的python dict:

my_dict = {'find': ['http://time.com', 'http://find.com'], 'time': ['http://any.com', 'http://www.tim.com', 'http://mine.in']...}
我想在mysql表的两个不同列中插入dictionary
my_dict
键和
值。列名称分别是
term
url
。我现在有三列:
id
term
url
我想在不同的行中插入每个键和值对。

我想将链接存储在
url
中,以逗号分隔。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查询并导致问题的列表

如果您希望在“值”部分中为每个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))
以逗号分隔格式存储URL

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))

您是否检查了正在生成的SQL是否符合预期?为什么不想使用某种ORM工具包<例如,code>sqlalchemy
。哦,不,对不起,我想在URL中存储以逗号分隔的链接,这意味着我想删除方形和双倒逗号,只是更新了答案以显示存储以逗号分隔的URL
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))