[Tutor] Passing a list, dict or tuple to MySQLdb?

Alan Wardroper python at wardroper.org
Fri Mar 16 21:53:26 CET 2007


 > I think what you want is ...(*list_of_tuples) similar to the syntax used
 > when calling functions with position arguments from a list.

Thanks, that bypasses the "TypeError: not all arguments converted during 
string formatting" error but raises a new error
    
"TypeError: execute() takes at most 3 arguments (5877 given)"

Looks like the elements of the list are being passed in as individual 
arguments rather than a formatted list.
So, for the simplest case...

I tried various versons of that cursor.execute including all variants 
with/without parentheses around %s &&|| list_of_ids:

If I include one %s substitution for each element in the list, it works, 
but that raises the question of how to do it when you don't know the 
size of the list beforehand?

So, for a 5 element list, this works:
CODE:
cursor.execute("SELECT field1, field2 FROM sometable WHERE field1 IN 
(%s, %s, %s, %s, %s)", list_of_ids)

But when the list is generated by a previous select statement...?

I dug through the docs a bit I pulled out executemany(), and so this 
seems to work:

cursor.executemany("SELECT field1, field2 FROM sometable WHERE field1 IN 
(%s)", (list_of_ids))

Thanks


More information about the Tutor mailing list