0

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,))
Brisi
  • 1,781
  • 7
  • 26
  • 41
  • 1
    possible duplicate of [Executing "SELECT ... WHERE ... IN ..." using MySQLdb](http://stackoverflow.com/questions/4574609/executing-select-where-in-using-mysqldb) – cwallenpoole Feb 18 '15 at 12:45

2 Answers2

3

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.

Community
  • 1
  • 1
Duniyadnd
  • 4,013
  • 1
  • 22
  • 29
1

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)
cwallenpoole
  • 79,954
  • 26
  • 128
  • 166