Solve Python MySQL insert int data error: typeerror% d format: a number is required, not str

Today, when using Python to crawl data and write it to MySQL database, the following statement is used:

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

  

The error is as follows:

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

Solution: the format string is not really a normal Python format string. You must always use% sfor all fields

That is to say, the string format of mysqldb is not the standard Python string format, and% s should always be used for string format

So change the value format of the SQL statement of the code to% s (no matter what type of data you want to insert), and it will run normally

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

  

Similar Posts: