Skip to content Skip to sidebar Skip to footer

Python Mysql Executemany In Where Clause

I want to select values from MySQL as follows do_not_select = [1,2,3] cursor = database.cursor() cursor.executemany('''SELECT * FROM table_a WHERE id != %s''',(do_not_select))

Solution 1:

Give NOT IN a go:

do_not_select = [1, 2, 3]

cursor.execute("""SELECT * FROM table_a
                    WHERE id NOT IN ({}, {}, {})""".format(do_not_select[0],
                                                           do_not_select[1],
                                                           do_not_select[2]))
data.cursor.fetchall()

I suspect (though I haven't tested this) that this would work better id do_not_select was a tuple, then I think you could just fire it straight into your query:

do_not_select = (1, 2, 3)
cursor.execute("""SELECT * FROM table_a
                    WHERE id NOT IN {}""".format(do_not_select))
data.cursor.fetchall()

I'd be interested to know if this works - if you try it please let me know :)

Post a Comment for "Python Mysql Executemany In Where Clause"