python list in sql query as parameter

后端 未结 15 1627
耶瑟儿~
耶瑟儿~ 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:52

    This uses parameter substitution and takes care of the single value list case:

    l = [1,5,8]
    
    get_operator = lambda x: '=' if len(x) == 1 else 'IN'
    get_value = lambda x: int(x[0]) if len(x) == 1 else x
    
    query = 'SELECT * FROM table where id ' + get_operator(l) + ' %s'
    
    cursor.execute(query, (get_value(l),))
    

提交回复
热议问题