sql查询中的python列表作为param

2024-05-14 09:15:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python列表,比如说

l = [1,5,8]

我想编写一个sql查询来获取列表中所有元素的数据,比如

select name from students where id = |IN THE LIST l|

我该怎么做?


Tags: the数据nameinfromid元素列表
3条回答

你想要的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)) + ')'

函数map将把列表转换成字符串列表,这些字符串可以使用str.join方法用逗号粘合在一起。

或者:

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

如果您喜欢generator expressions而不是map函数。

更新:S. Lott在注释中提到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)

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

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

相关问题 更多 >

    热门问题