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

今天在使用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

解决方案:The format string is not really a normal Python format string. Youmust always use %s for 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()

  

猜你喜欢

转载自www.cnblogs.com/wang-jx/p/12313865.html