Python MySQLdb问题(TypeError:%d格式:需要一个数字,而不是str)

时间:2011-04-26 02:01:49

标签: python insertion mysql-python

我正在尝试执行以下插入操作:

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

我的MYSQL表的结构是:

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

然而,当我运行程序时,我收到错误

  

“文件”/usr/lib/pymodules/python2.6/MySQLdb/cursors.py“,第151行,执行中       query = query%db.literal(args)

     

TypeError:%d format:需要一个数字,而不是str“

5 个答案:

答案 0 :(得分:138)

格式字符串实际上不是普通的Python格式字符串。您必须始终对所有字段使用%s

答案 1 :(得分:0)

试试这个:

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

答案 2 :(得分:0)

由于他的数据是整数或十进制格式,你如何使用%s,通常用于字符串格式%d或%i应该用于整数或十进制值。

答案 3 :(得分:0)

每当您看到该类型的错误时,都应使用type()函数检查值或变量的类型....,并且会看到类型为-'str'。意味着python接受字符串中的所有值(默认数据类型为string)。这就是为什么错误说%d是数字,而不是字符串。因此,对于每种类型的字段,请考虑使用python中的%s。

答案 4 :(得分:0)

我遇到了同样的错误,但这是出于不同的原因。问题在于该字符串包含一个'%'并且混淆了Python:

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

Python将“%discount”解释为“%d”,并不断抱怨,因为我给它提供了字符串('abc'),而不是数字。

我花了很长时间才能弄清楚!

(解决方案是键入%%而不是%。)