Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
722 views
in Technique[技术] by (71.8m points)

mysql - MySQLdb Python insert %d and %s

Precursor:

MySQL Table created via:
CREATE TABLE table(Id INT PRIMARY KEY NOT NULL, Param1 VARCHAR(50))

Function:

.execute("INSERT INTO table VALUES(%d,%s)", (int(id), string)

Output:

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

I'm not sure what's going on here or why I am not able to execute the command. This is using MySQLdb in Python. .execute is performed on a cursor object.

EDIT:

The question: Python MySQLdb issues (TypeError: %d format: a number is required, not str) says that you must use %s for all fields. Why might this be? Why does this command work?

.execute("INSERT INTO table VALUES(%s,%s)", (int(id), string)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As the whole query needs to be in a string format while execution of query so %s should be used...

After query is executed integer value is retained.

So your line should be.

.execute("INSERT INTO table VALUES(%s,%s)", (int(id), string))

Explanation is here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...