简体   繁体   English

python字典插入到mysql

[英]python dictionary insert to mysql

I am trying to take the data from a dictionary and insert it into a mysql database. 我试图从字典中获取数据并将其插入到mysql数据库中。 I have the following piece of code. 我有以下代码。

 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 在此输入图像描述

This happens because there is an interger in your list vals . 这是因为有您的列表中的整数vals So you need to cast it to string. 所以你需要将它转换成字符串。 Modify your code as below. 修改您的代码如下。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM