python list in sql query as parameter

后端 未结 15 1628
耶瑟儿~
耶瑟儿~ 2020-11-22 09:39

I have a python list, say l

l = [1,5,8]

I want to write a sql query to get the data for all the elements of the list, say

s         


        
15条回答
  •  無奈伤痛
    2020-11-22 09:46

    If you're using PostgreSQL with the Psycopg2 library you can let its tuple adaption do all the escaping and string interpolation for you, e.g:

    ids = [1,2,3]
    cur.execute(
      "SELECT * FROM foo WHERE id IN %s",
      [tuple(ids)])
    

    i.e. just make sure that you're passing the IN parameter as a tuple. if it's a list you can use the = ANY array syntax:

    cur.execute(
      "SELECT * FROM foo WHERE id = ANY (%s)",
      [list(ids)])
    

    note that these both will get turned into the same query plan so you should just use whichever is easier. e.g. if your list comes in a tuple use the former, if they're stored in a list use the latter.

提交回复
热议问题