Python MySQLdb 问题(类型错误:%d 格式:需要数字,而不是 str)
我正在尝试执行以下插入操作:
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 行,执行中 查询 = 查询 % db.literal(args)
类型错误:%d 格式:需要数字,而不是 str"
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"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
该格式字符串实际上并不是普通的 Python 格式字符串。您必须始终对所有字段使用
%s
。参考官方文档:
->也就是说:这里
%s
是不是格式化程序,但是是占位符The format string is not really a normal Python format string. You must always use
%s
for all fields.refer official document:
-> that is: here
%s
is NOT formatter, but is a placeholder我遇到了同样的错误,但原因不同。问题是该字符串包含一个“%”,这让 Python 感到困惑:
Python 将“%折扣”解释为“%d”并一直抱怨,因为我向它提供了一个字符串(“abc”),而不是一个数字。
我花了很长时间才弄清楚!
(解决方案是键入 %% 而不是 %。)
I got the same error, but it was for a different reason. The problem was that the string included a '%' and that confused Python:
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 time to figure it out!
(The solution is to type %% instead of %.)
基于这个答案 https://stackoverflow.com/a/46517683/1564659
我最终使用
%s< /code> 即使对于浮点数和数字也是如此。插入到表中并且SQL检测到表数据类型后会立即转换
Based on this answer https://stackoverflow.com/a/46517683/1564659
I finally use
%s
even for floats and digits. It will be converted right away when inserted to the table and SQL detected the table data type试试这个:
try this :
由于他的数据是整数或小数格式,你怎么能使用通常用于字符串格式%d或%i的%s来表示整数或小数值。
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.
每当你看到这种类型的错误时,应该使用 type() 函数来检查值或变量的类型......,并且会看到类型是 - 'str'。意味着 python 获取字符串中的所有值(默认数据类型是字符串)。这就是为什么错误说 %d 适用于数字,而不适用于字符串。因此,请考虑在 python 中对每种类型的字段使用 %s。
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.