使用python sqlite3从sqlite表中选择rowid in list — DB-API 2.0 [英] select from sqlite table where rowid in list using python sqlite3 — DB-API 2.0

查看:28
本文介绍了使用python sqlite3从sqlite表中选择rowid in list — DB-API 2.0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下工作:

<预><代码>>>>cursor.execute("select * from sqlitetable where rowid in (2,3);")

以下不是:

<预><代码>>>>cursor.execute("select * from sqlitetable where rowid in (?) ", [[2,3]] )sqlite3.InterfaceError:错误绑定参数 0 - 可能不受支持的类型.

有没有办法传入python列表而不必先将其格式化为字符串?

解决方案

很遗憾没有.每个值都必须有自己的参数标记 (?).由于参数列表可以(大概)具有任意长度,因此您必须使用字符串格式来构建正确数量的参数标记.令人高兴的是,这并不难:

args=[2,3]sql="select * from sqlitetable where rowid in ({seq})".format(seq=','.join(['?']*len(args)))cursor.execute(sql, args)

The following works:

>>> cursor.execute("select * from sqlitetable where rowid in (2,3);")

The following doesn't:

>>> cursor.execute("select * from sqlitetable where rowid in (?) ", [[2,3]] )
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.

Is there a way to pass in a python list without having to format it into a string first ?

解决方案

Unfortunately not. Each value must be given its own parameter mark (?). Since the argument list can (presumably) have arbitrary length, you must use string formating to build the correct number of parameter marks. Happily, that isn't so hard:

args=[2,3]
sql="select * from sqlitetable where rowid in ({seq})".format(
    seq=','.join(['?']*len(args)))

cursor.execute(sql, args)

这篇关于使用python sqlite3从sqlite表中选择rowid in list — DB-API 2.0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆