python list in sql query as parameter

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

    I like bobince's answer:

    placeholder= '?' # For SQLite. See DBAPI paramstyle.
    placeholders= ', '.join(placeholder for unused in l)
    query= 'SELECT name FROM students WHERE id IN (%s)' % placeholders
    cursor.execute(query, l)
    

    But I noticed this:

    placeholders= ', '.join(placeholder for unused in l)
    

    Can be replaced with:

    placeholders= ', '.join(placeholder*len(l))
    

    I find this more direct if less clever and less general. Here l is required to have a length (i.e. refer to an object that defines a __len__ method), which shouldn't be a problem. But placeholder must also be a single character. To support a multi-character placeholder use:

    placeholders= ', '.join([placeholder]*len(l))
    

提交回复
热议问题