Python MySQLdb issues (TypeError:

2019-01-16 13:28发布

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"

4条回答
别忘想泡老子
2楼-- · 2019-01-16 14:06

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)
                    )
查看更多
走好不送
3楼-- · 2019-01-16 14:16

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.

查看更多
狗以群分
4楼-- · 2019-01-16 14:26

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.

查看更多
Luminary・发光体
5楼-- · 2019-01-16 14:27

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

查看更多
登录 后发表回答