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()
    

      

  • 相关阅读:
    C++ Primer 笔记——语句
    C++ Primer 笔记——const 限定符
    C++ Primer 笔记——变量
    C++ Primer 笔记——函数
    C++ Primer 笔记——基本内置类型
    图的遍历算法:DFS、BFS
    python数据结构之图论
    下载文件的协议:HTTP、FTP、P2P
    HTTPS协议
    HTTP协议
  • 原文地址:https://www.cnblogs.com/wang-jx/p/12313865.html
Copyright © 2011-2022 走看看