SQL查询中的Python列表作为参数

SQL查询中的Python列表作为参数

我有一张蟒蛇名单,比如说我

l = [1,5,8]

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

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

我该如何做到这一点?


慕森卡
浏览 995回答 3
3回答

白衣染霜花

到目前为止,答案是将值模板为普通的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)

紫衣仙女

不要把它复杂化,解决这个问题很简单。l = [1,5,8]l = tuple(l)params = {'l': l}cursor.execute('SELECT * FROM table where id in %(l)s',params)我希望这能帮上忙!

慕妹3242003

您想要的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)) + ')'如果你愿意生成器表达式映射函数。最新情况:S.Lott注释中提到PythonSQLite绑定不支持序列。在这种情况下,你可能想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))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python
MySQL