MySQLdb Python insert %d and %s

偶尔善良 提交于 2019-12-20 10:11:44

问题


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)

回答1:


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




回答2:


The format string is not really a normal Python format string. You must always use %s for all fields




回答3:


You missed a '%' in string formatting

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


来源:https://stackoverflow.com/questions/20463333/mysqldb-python-insert-d-and-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!