Python sqlite参数扩展问题
我有一个包含三列的表格,cell
、trx
和 type
。 这是我尝试运行的查询:
db.execute("SELECT cell,trx FROM tchdrop").fetchall()
它给出了正确的输出。
但是,当我尝试 a = ("cell", "trx")
然后
db.execute("SELECT ?,? FROM tchdrop", t).fetchall()
输出为 [(u'cell', u'trx'), (u'cell', u 'trx')]
(这是错误的)
我这样做是为了弄清楚如何动态提取列,这是一个更大问题的一部分。
I have a table with three columns, cell
, trx
and type
.
This is the query I'm trying to run:
db.execute("SELECT cell,trx FROM tchdrop").fetchall()
It gives the correct output.
However when I try a = ("cell", "trx")
and then
db.execute("SELECT ?,? FROM tchdrop", t).fetchall()
the output is [(u'cell', u'trx'), (u'cell', u'trx')]
(which is wrong)
I'm doing this to figure out how to extract columns dynamically which is a part of a bigger problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
python DB-API(如sqlite3)的占位符(?)不支持传递列名称,因此您必须使用像这样的python字符串格式:
编辑:
如果您不知道列的长度,你想通过,你可以这样做:
The place holder (?) of python DB-API (like sqlite3) don't support columns names to be passed, so you have to use python string formatting like this:
EDIT:
if you don't know the length of the columns that you want to pass , you can do something like this:
该库将指定的值
("cell", "trx")
替换为其引用的 SQL 等效值,因此您得到的是SELECT "cell", "trx" FROM tchdrop
。结果是正确的。使用
?
语法无法实现您想要实现的目标。相反,您自己更换字符串。您可以使用正则表达式(例如^[a-zA-Z_]$
)检查列名称以提高安全性。例如:
The library replaces the specified values
("cell", "trx")
with their quoted SQL equivalent, so what you get isSELECT "cell", "trx" FROM tchdrop
. The result is correct.What you are trying to achieve is not possible with the
?
syntax. Instead, do string replacement yourself. You can check column names with regular expressions (like^[a-zA-Z_]$
) for more security.For example: