sql查询中的python列表作为参数

sql查询中的python列表作为参数,python,sql,Python,Sql,我有一个python列表,比如说l l = [1,5,8] 我想编写一个sql查询来获取列表中所有元素的数据,比如 select name from students where id = |IN THE LIST l| 如何完成此操作?使用逗号分隔的列表值,并使用来形成查询字符串 myquery = "select name from studens where id in (%s)" % ",".join(map(str,mylist)) (谢谢,)用逗号分隔的列表值,并使用组成查询字

我有一个python列表,比如说l

l = [1,5,8]
我想编写一个sql查询来获取列表中所有元素的数据,比如

select name from students where id = |IN THE LIST l|
如何完成此操作?

使用逗号分隔的列表值,并使用来形成查询字符串

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

用逗号分隔的列表值,并使用组成查询字符串

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

您需要的SQL是

select name from studens where id in (1, 5, 8)
如果您想从python构建它,可以使用

l = [1, 5, 8]
sql_query = 'select name from studens where id in (' + ','.join(map(str, l)) + ')'
该函数将列表转换为字符串列表,可以使用该方法使用逗号将这些字符串粘在一起

或者:

l = [1, 5, 8]
sql_query = 'select name from studens where id in (' + ','.join((str(n) for n in l)) + ')'
如果您喜欢map函数

更新:注释中提到Python SQLite绑定不支持序列。在这种情况下,您可能需要

select name from studens where id = 1 or id = 5 or id = 8
产生于

sql_query = 'select name from studens where ' + ' or '.join(('id = ' + str(n) for n in l))
您想要的SQL是

select name from studens where id in (1, 5, 8)
如果您想从python构建它,可以使用

l = [1, 5, 8]
sql_query = 'select name from studens where id in (' + ','.join(map(str, l)) + ')'
该函数将列表转换为字符串列表,可以使用该方法使用逗号将这些字符串粘在一起

或者:

l = [1, 5, 8]
sql_query = 'select name from studens where id in (' + ','.join((str(n) for n in l)) + ')'
如果您喜欢map函数

更新:注释中提到Python SQLite绑定不支持序列。在这种情况下,您可能需要

select name from studens where id = 1 or id = 5 or id = 8
产生于

sql_query = 'select name from studens where ' + ' or '.join(('id = ' + str(n) for n in l))

到目前为止,答案是将这些值模板化为一个简单的SQL字符串。这对于整数来说是绝对好的,但是如果我们想对字符串这样做,我们就会遇到转义问题

下面是一个使用参数化查询的变体,该查询将同时适用于以下两种情况:

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)

到目前为止,答案是将这些值模板化为一个简单的SQL字符串。这对于整数来说是绝对好的,但是如果我们想对字符串这样做,我们就会遇到转义问题

下面是一个使用参数化查询的变体,该查询将同时适用于以下两种情况:

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)

我喜欢bobince的回答:

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)
可替换为:

placeholders= ', '.join(placeholder*len(l))
我觉得这更直接,如果不那么聪明和一般。此处要求
l
具有长度(即,引用定义
方法的对象),这应该不是问题。但占位符也必须是单个字符。要支持多字符占位符,请使用:

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

我喜欢bobince的回答:

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)
可替换为:

placeholders= ', '.join(placeholder*len(l))
我觉得这更直接,如果不那么聪明和一般。此处要求
l
具有长度(即,引用定义
方法的对象),这应该不是问题。但占位符也必须是单个字符。要支持多字符占位符,请使用:

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

@umounted answer的解决方案,因为它与一个元素元组断开,因为(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)+'"'))

@umounted answer的解决方案,因为它与一个元素元组断开,因为(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)+'"'))

例如,如果需要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(']',')') )

例如,如果需要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,5,8]

l = tuple(l)

params = {'l': l}

cursor.execute('SELECT * FROM table where id in %(l)s',params)


我希望这有帮助

不要把它复杂化,解决方法很简单

l = [1,5,8]

l = tuple(l)

params = {'l': l}

cursor.execute('SELECT * FROM table where id in %(l)s',params)


我希望这有帮助

最简单的方法是首先将列表转到
tuple

t = tuple(l)
query = "select name from studens where id IN {}".format(t)

最简单的方法是首先将列表转到
tuple

t = tuple(l)
query = "select name from studens where id IN {}".format(t)

这将使用参数替换并考虑单值列表的情况:

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),))

这将使用参数替换并考虑单值列表的情况:

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),))
这应该能解决你的问题

这将解决您的问题。

一个更简单的解决方案:

lst = [1,2,3,a,b,c]

query = f"""SELECT * FROM table WHERE IN {str(lst)[1:-1}"""
更简单的解决方案:

lst = [1,2,3,a,b,c]

query = f"""SELECT * FROM table WHERE IN {str(lst)[1:-1}"""

如果您将PostgreSQL与Psycopg2库一起使用,您可以让它为您执行所有转义和字符串插值,例如:

ids = [1,2,3]
cur.execute(
  "SELECT * FROM foo WHERE id IN %s",
  [tuple(ids)])
i、 e.只需确保将
作为
元组
传入
参数即可。如果是
列表
,您可以使用:


请注意,这两个查询都将转换为相同的查询计划,因此您应该使用更简单的查询计划。e、 g.如果列表是元组,请使用元组;如果列表存储在元组中,请使用元组。

如果您将PostgreSQL与Psycopg2库一起使用,则可以让它为您执行所有转义和字符串插值,例如:

ids = [1,2,3]
cur.execute(
  "SELECT * FROM foo WHERE id IN %s",
  [tuple(ids)])
l = [1] # or [1,2,3]

query = "SELECT * FROM table WHERE id IN :l"
params = {'l' : tuple(l)}
cursor.execute(query, params)
i、 e.只需确保将
作为
元组
传入
参数即可。如果是
列表
,您可以使用:

请注意,这两个查询都将转换为相同的查询计划,因此您应该使用更简单的查询计划。e、 如果你的列表是一个元组,那么使用前者,如果它们存储在一个列表中,那么使用后者

l = [1] # or [1,2,3]

query = "SELECT * FROM table WHERE id IN :l"
params = {'l' : tuple(l)}
cursor.execute(query, params)
:var
符号似乎更简单。(Python 3.7)


:var
符号似乎更简单。(Python3.7)

如果列表中的值的数量等于1或大于1,则这将起作用

t = str(tuple(l))
if t[-2] == ',':
   t= t.replace(t[-2],"")
query = "select name from studens where id IN {}".format(t)

如果列表中的值数等于1或大于1,则此操作将起作用

t = str(tuple(l))
if t[-2] == ',':
   t= t.replace(t[-2],"")
query = "select name from studens where id IN {}".format(t)

只需将内联if操作与元组函数一起使用:

query = "Select * from hr_employee WHERE id in " % tuple(employee_ids) if len(employee_ids) != 1 else "("+ str(employee_ids[0]) + ")"

只需将内联if操作与元组函数一起使用:

query = "Select * from hr_employee WHERE id in " % tuple(employee_ids) if len(employee_ids) != 1 else "("+ str(employee_ids[0]) + ")"

要运行select from字段在字符串列表中的位置(而不是int),请使用
repr(tuple(map(str,l))
。完整示例:

l = ['a','b','c']
sql = f'''

select name 
from students 
where id in {repr(tuple(map(str, l)))}
'''
print(sql)
返回:
从id位于('a','b','c')的学生中选择姓名。

对于Oracle中的日期列表,这是有效的

dates_str = ','.join([f'DATE {repr(s)}' for s in ['2020-11-24', '2020-12-28']])
dates_str = f'({dates_str})'

sql_cmd = f'''
select *
from students 
where 
and date in {dates_str}
'''
返回:
select*from students where and date in(日期'2020-11-24',日期'2020-12-28')
要运行select from字段在字符串列表中的位置(而不是int),请使用
repr(元组(map(str,l)))
。完整示例:

l = ['a','b','c']
sql = f'''

select name 
from students 
where id in {repr(tuple(map(str, l)))}
'''
print(sql)
返回:
从id位于('a','b','c')的学生中选择姓名。

对于Oracle中的日期列表,这是有效的

dates_str = ','.join([f'DATE {repr(s)}' for s in ['2020-11-24', '2020-12-28']])
dates_str = f'({dates_str})'

sql_cmd = f'''
select *
from students 
where 
and date in {dates_str}
'''
返回:
select*来自学生的位置和日期(日期'2020-11-24',日期'2020-12-28')

:-(Python-SQLite绑定不支持序列。哦?我没有意识到。然后,我再次强调,我没有意识到我们要使用SQLite绑定解决方案。对不起,没有建议或暗示SQLite——只是遗憾的是绑定是为li准备的