SQL查询中的Python列表作为参数我有一张蟒蛇名单,比如说我l = [1,5,8]我想编写一个SQL查询来获取列表中所有元素的数据,比如select name from students where id = |IN THE LIST l|我该如何做到这一点?
3 回答
白衣染霜花
TA贡献1796条经验 获得超10个赞
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)
紫衣仙女
TA贡献1839条经验 获得超15个赞
l = [1,5,8]l = tuple(l)params = {'l': l}cursor.execute('SELECT * FROM table where id in %(l)s',params)
慕妹3242003
TA贡献1824条经验 获得超6个赞
select name from studens where id in (1, 5, 8)
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)) + ')'
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))
添加回答
举报
0/150
提交
取消