解决python mysql插入数据时报错:TypeError: %d format: a number is required, not str,,今天在使用pytho


今天在使用python爬取数据并将其写入mysql数据库时,使用该如下语句:

       cursor.execute(                    "insert into comments_p_spider(owner_id,from_name,content,create_time,score,comment_level) values(%d,%s,%s,%s,%f,%s)",                    (p_id,str(username), str(contentStr), str(create_time),float(score), str(comment_level)))            conn.commit()

  

报错如下:

技术图片

TypeError: %d format: a number is required, not str

解决方案:Theformat string isnot really a normal Pythonformat string. Youmust alwaysuse%sfor all fields.

也就是MySQLdb的字符串格式化不是标准的python的字符串格式化,应当一直使用%s用于字符串格式化。

所以将代码的sql语句的value格式均改为%s(无论要插入的数据是什么类型),即可正常运行。

        cursor.execute(                    "insert into comments_p_spider(owner_id,from_name,content,create_time,score,comment_level) values(%s,%s,%s,%s,%s,%s)",                    (p_id,str(username), str(contentStr), str(create_time),float(score), str(comment_level)))            conn.commit()

  

解决python mysql插入数据时报错:TypeError: %d format: a number is required, not str

评论关闭