python list in sql query as parameter

后端 未结 15 1424
耶瑟儿~
耶瑟儿~ 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 10:04

    The SQL you want is

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

    If you want to construct this from the python you could use

    l = [1, 5, 8]
    sql_query = 'select name from studens where id in (' + ','.join(map(str, l)) + ')'
    

    The map function will transform the list into a list of strings that can be glued together by commas using the str.join method.

    Alternatively:

    l = [1, 5, 8]
    sql_query = 'select name from studens where id in (' + ','.join((str(n) for n in l)) + ')'
    

    if you prefer generator expressions to the map function.

    UPDATE: S. Lott mentions in the comments that the Python SQLite bindings don't support sequences. In that case, you might want

    select name from studens where id = 1 or id = 5 or id = 8
    

    Generated by

    sql_query = 'select name from studens where ' + ' or '.join(('id = ' + str(n) for n in l))
    
    0 讨论(0)
  • 2020-11-22 10:05

    Dont complicate it, Solution for this is simple.

    l = [1,5,8]
    
    l = tuple(l)
    
    params = {'l': l}
    
    cursor.execute('SELECT * FROM table where id in %(l)s',params)
    

    I hope this helped !!!

    0 讨论(0)
  • 2020-11-22 10:05

    This Will Work If Number of Values in List equals to 1 or greater than 1

    t = str(tuple(l))
    if t[-2] == ',':
       t= t.replace(t[-2],"")
    query = "select name from studens where id IN {}".format(t)
    
    0 讨论(0)
提交回复
热议问题