python list in sql query as parameter

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

    Solution for @umounted answer, because that broke with a one-element tuple, since (1,) is not valid SQL.:

    >>> random_ids = [1234,123,54,56,57,58,78,91]
    >>> cursor.execute("create table test (id)")
    >>> for item in random_ids:
        cursor.execute("insert into test values (%d)" % item)
    >>> sublist = [56,57,58]
    >>> cursor.execute("select id from test where id in %s" % str(tuple(sublist)).replace(',)',')'))
    >>> a = cursor.fetchall()
    >>> a
    [(56,), (57,), (58,)]
    

    Other solution for sql string:

    cursor.execute("select id from test where id in (%s)" % ('"'+'", "'.join(l)+'"'))
    

提交回复
热议问题