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

user721975 picture user721975 · Apr 26, 2011 · Viewed 74k times · Source

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"

Answer

Keith picture Keith · Apr 26, 2011

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