gpt4 book ai didi

python字典插入到mysql

转载 作者:行者123 更新时间:2023-11-30 22:00:48 24 4
gpt4 key购买 nike

我正在尝试从字典中获取数据并将其插入到 mysql 数据库中。我有以下代码。

import pymysql

connect = pymysql.Connect(
host='localhost',
port=3306,
user='root',
passwd='my729501s',
db='major',
charset='utf8'
)
data = {'video_title': 'hanzi', 'id': 1, 'video_url': 'www.bad.com', 'image_url': 'www.baidu.com', 'subject_title': 'nothong'}
cursor = connect.cursor()
table = 'video_title'
cols = data.keys()
vals = data.values()
sql = "INSERT INTO %s (%s) VALUES(%s)" % (table, ",".join(cols), ",".join(vals))

cursor.execute(sql)

connect.commit()
connect.close()
cursor.close()
enter image description here

最佳答案

发生这种情况是因为列表 vals 中有一个整数。所以你需要把它转换成字符串。如下修改您的代码。

sql = "INSERT INTO %s (%s) VALUES(%s)" % (table, ",".join(cols), ",".join(str(x) for x in vals))

关于python字典插入到mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43427304/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com