python list in sql query as parameter

后端 未结 15 1425
耶瑟儿~
耶瑟儿~ 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))
    
    0 讨论(0)
  • 2020-11-22 09:50

    Easiest way is to turn the list to tuple first

    t = tuple(l)
    query = "select name from studens where id IN {}".format(t)
    
    0 讨论(0)
  • 2020-11-22 09:51

    string.join the list values separated by commas, and use the format operator to form a query string.

    myquery = "select name from studens where id in (%s)" % ",".join(map(str,mylist))
    

    (Thanks, blair-conrad)

    0 讨论(0)
  • 2020-11-22 09:51

    For example, if you want the sql query:

    select name from studens where id in (1, 5, 8)
    

    What about:

    my_list = [1, 5, 8]
    cur.execute("select name from studens where id in %s" % repr(my_list).replace('[','(').replace(']',')') )
    
    0 讨论(0)
  • 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),))
    
    0 讨论(0)
  • 2020-11-22 10:03

    a simpler solution:

    lst = [1,2,3,a,b,c]
    
    query = f"""SELECT * FROM table WHERE IN {str(lst)[1:-1}"""
    
    0 讨论(0)
提交回复
热议问题