Problems with Python MySQLdb (TypeError:% d format: number is required, not str)

I am trying to perform 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:

 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 an error

"File" / usr / lib / pymodules / python 2.6 / MySQLdb / cursors.py ", line 151, executed by query = query% db.literal (args)

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

+59
python mysql-python insertion
Apr 26 '11 at 2:01
source share
6 answers

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

+142
Apr 26 2018-11-11T00:
source share

try the following:

 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) ) 
0
Aug 12 '13 at 14:19
source share

Since its data is in integer or decimal format, as you can use% s, which is usually used for string format,% d or% I should use for integer or decimal values.

0
Jan 21 '17 at 10:36 on
source share

Whenever you see errors of this type, you should use the type () function to check the types of values ​​or variables .... and you will see the type is - 'str'. This means that Python accepts all values ​​in strings (the default data type is string). Therefore, the error says that% d is for numbers, not strings. Therefore, consider% s in python for all field types.

0
Oct 03 '18 at 18:38
source share

I got the same error, but that was for a different reason. The problem was that the string contained the "%" character and this was confusing to Python:

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

Python interpreted this β€œ% discount” as β€œ% d” and kept complaining because I fed it with a string ('abc') rather than a number.

It took me a long time to figure this out!

(The solution is to enter %% instead of%.)

0
Mar 13 '19 at 0:14
source share

enter image description here Here we rather write & d, set% s for everything.

0
Jul 15 '19 at 17:41
source share



All Articles