zoukankan      html  css  js  c++  java
  • 解决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()
    

      

  • 相关阅读:
    linux
    算法
    算法
    数据结构 与 算法
    mysql
    mysql
    mysql
    mysql
    【解决】Could not get JDBC Connection、java.lang.InterruptedException问题和排查过程
    git: unable to checkout working tree error: unable to create file Filename too long on windows
  • 原文地址:https://www.cnblogs.com/wang-jx/p/12313865.html
Copyright © 2011-2022 走看看