How to select many rows from a dictionary (executemany select)

2.8k Views Asked by At

I'm using Python and its MySQLdb module, is it possible to do a "selectmany"-like from a tuple/dictionary/list in the condition

something like this:

cursor.executemany("""SELECT * FROM customers WHERE name= %(name)s""",[d.__dict__ for d in data])

selected_rows = cursor.fecthall()

doing a delete/update/insert works fine with this method :

cursor.executemany("""UPDATE customers SET item = %(item)s WHERE name = %(name)s""",[d.__dict__ for d in data])
3

There are 3 best solutions below

1
On BEST ANSWER

You could use the "WHERE IN" sql syntax, for example,

SELECT * FROM customers WHERE name IN ('john', 'mary', 'jane');
0
On

I haven't used the executemany method yet, but I wonder if it's meant to be used for SELECTs. What about

... where name in (...)

instead of

... where name = ...

and inserting a tuple containing the keys of your data dictionaries?

0
On

executemany for the most part is for insertion or update. Doesn't really work well for querying data, from my experience it will only return the last set of parameters.