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)
Answers so far have been templating the values into a plain SQL string. That’s absolutely fine for integers, but if we wanted to do it for strings we get the escaping issue.
Here’s a variant using a parameterised query that would work for both:
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)
回答 1
最简单的方法是将列表转到tuple第一
t = tuple(l)
query ="select name from studens where id IN {}".format(t)
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)
但是我注意到了这一点:
placeholders=', '.join(placeholder for unused in l)
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))
回答 6
@umount答案的解决方案,因为它用一个元素的元组中断,因为(1,)不是有效的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,)]
sql字符串的其他解决方案:
cursor.execute("select id from test where id in (%s)"%('"'+'", "'.join(l)+'"'))
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)+'"'))
回答 7
placeholders=', '.join("'{"+str(i)+"}'"for i in range(len(l)))
query="select name from students where id (%s)"%placeholders
query=query.format(*l)
cursor.execute(query)
placeholders= ', '.join("'{"+str(i)+"}'" for i in range(len(l)))
query="select name from students where id (%s)"%placeholders
query=query.format(*l)
cursor.execute(query)
If you’re using PostgreSQL with the Psycopg2 library you can let its tuple adaption do all the escaping and string interpolation for you, e.g:
ids = [1,2,3]
cur.execute(
"SELECT * FROM foo WHERE id IN %s",
[tuple(ids)])
i.e. just make sure that you’re passing the IN parameter as a tuple. if it’s a list you can use the = ANY array syntax:
cur.execute(
"SELECT * FROM foo WHERE id = ANY (%s)",
[list(ids)])
note that these both will get turned into the same query plan so you should just use whichever is easier. e.g. if your list comes in a tuple use the former, if they’re stored in a list use the latter.
回答 9
例如,如果要使用sql查询:
select name from studens where id in(1,5,8)
关于什么:
my_list =[1,5,8]
cur.execute("select name from studens where id in %s"% repr(my_list).replace('[','(').replace(']',')'))
l = [1] # or [1,2,3]
query = "SELECT * FROM table WHERE id IN :l"
params = {'l' : tuple(l)}
cursor.execute(query, params)
The :var notation seems simpler. (Python 3.7)
回答 12
这使用参数替换并处理单个值列表的情况:
l =[1,5,8]
get_operator =lambda x:'='if len(x)==1else'IN'
get_value =lambda x:int(x[0])if len(x)==1else x
query ='SELECT * FROM table where id '+ get_operator(l)+' %s'
cursor.execute(query,(get_value(l),))