Python MySQL executemany in WHERE clause

大憨熊 提交于 2019-12-11 00:10:01

问题


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))
data = cursor.fetchall()

The query return all the values in the db apart form the first id (1). I don't want it to select id 1,2 or 3 however.

Is this possible using the executemany command..?


回答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 :)



来源:https://stackoverflow.com/questions/18294248/python-mysql-executemany-in-where-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!