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

匿名 (未验证) 提交于 2019-12-03 01:29:01

问题:

I am trying to do the following insert operation:

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

The structure of my MYSQL table is:

id int(255), parent_id int(255), level int(11), description varchar(255), code varchar(255), start decimal(25,4), end decimal(25,4) 

However when I run my program, I get the error

" File "/usr/lib/pymodules/python2.6/MySQLdb/cursors.py", line 151, in execute query = query % db.literal(args)

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

回答1:

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



回答2:

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.



回答3:

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


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