python字典插入到mysql

标签 python mysql dictionary

我正在尝试从字典中获取数据并将其插入到 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/

相关文章:

python - 将 s3/cloudfront 与数据库同步的架构

python - 基于源-目标字典计算源路径

mysql - Rails 4 如何将图像作为 blob 加载到数据库中

php - 为什么它输出: the query is empty

c++ - 根据类成员对同一键的多映射元素进行排序?

python - 将多个列表数据转换为字典

python - 拆分数据时使用 scikit-learn 规范化 PCA

python - 根据 Pandas 中的外键减去多列

mysql - 选择变量的第二低 'id' 值

ios - 按下自定义 UITabBarController 上的按钮时显示用户位置