Python MySQLdb issues (TypeError: %d format: a number is required, not str)

有些话、适合烂在心里 提交于 2019-11-27 06:47:24
Keith

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

refer official document:

If args is a list or tuple, %s can be used as a placeholder in the query. If args is a dict, %(name)s can be used as a placeholder in the query.

-> that is: here %s is NOT formatter, but is a placeholder

orain

try this :

cursor.execute("""
                    insert into tree (id,parent_id,level,description,code,start,end)
                    values (%s,%s,%s,'%s','%s',%s,%s)
                    """%(1,1,1,'abc','def',1,1)
                    )

Since his data is in integer or decimal format how can you use %s which is usually used for string format %d or %i should be used for integer or decimal values.

Whenever you saw that type of errors, should use type() function for checking the types of values or variables...., and will see type is - 'str'. Means python takes all the values in strings (By default data type is string). That's why the error said %d is for numbers, Not for the strings. So consider %s in python for every types of field.

I got the same error, but it was for a different reason. The problem was that the string included a '%' and that confused Python:

TemplateStr = '[....] % discount rate  [....]  %s and %s
print TemplateStr % ('abc', 'def')

Python interpreted that "% discount" as "%d" and kept complaining because I was feeding it a string ('abc'), not a number.

It took me a long tome to figure it out!

(The solution is to type %% instead of %.)

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