Python-Warning: Truncated incorrect DOUBLE value

2019-09-05 22:33发布

问题:

I am trying to fetch "bar_ids" from "foo" table using mysql-python. To this end, I got the following error and I am receiving only few bar_ids. How do I get this correctly without warning error?

My table is shown below:

create table foo (foo_id int, bar_id int, foo_name varchar(255))

My query & Error:

foo_ids = 16600, 16602, 16607, 16609, 16611, 16613

Warning: Data truncated for column 'bar_id' at row 1

cursor.execute("""select bar_id from foo where foo_id in (%s)""", (foo_ids,))

Warning: Truncated incorrect DOUBLE value: '16600, 16602, 16607, 16609, 16611, 16613'

cursor.execute("""select bar_id from foo where foo_id in (%s)""", (foo_ids,))

回答1:

This question has been asked before in SO. Putting in a response so it might help to give some context and help @brisk read this sort of error going forward.

The problem is that it is taking 'foo_ids' as a string and not as individual values. So it's essentially trying to run:

select bar_id from foo where foo_id in ('16600, 16602, 16607, 16609, 16611, 16613') 

Notice the quotes? You want it to run:

select bar_id from foo where foo_id in (16600, 16602, 16607, 16609, 16611, 16613) 

so when you reported your error, it included 'quotes' around the numbers.

There are a few solutions that you can consider.



回答2:

Basically, you need to re-create the param list yourself:

param_list = '%s,' * (len(foo_ids) - 1) + '%s'
sql = """select bar_id from foo where foo_id in (%s)""" % param_list
cursor.execute(sql, foo_ids)