Python sqlite参数扩展问题

发布于 2024-10-21 08:21:23 字数 428 浏览 1 评论 0原文

我有一个包含三列的表格,celltrxtype。 这是我尝试运行的查询:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

爱她像谁 2024-10-28 08:21:23

python DB-API(如sqlite3)的占位符(?)不支持传递列名称,因此您必须使用像这样的python字符串格式:

a = ("cell", "trx")

query = "SELECT {0},{1} FROM tchdrop".format(*a)
db.execute(query)

编辑:

如果您不知道列的长度,你想通过,你可以这样做:

a = ("cell", "trx", "foo", "bar")
a = ", ".join(a)

query = "SELECT {0} FROM tchdrop".format(a)
# OUTPUT : 'SELECT cell, trx, foo, bar FROM tchdrop'
db.execute(query)

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:

a = ("cell", "trx")

query = "SELECT {0},{1} FROM tchdrop".format(*a)
db.execute(query)

EDIT:

if you don't know the length of the columns that you want to pass , you can do something like this:

a = ("cell", "trx", "foo", "bar")
a = ", ".join(a)

query = "SELECT {0} FROM tchdrop".format(a)
# OUTPUT : 'SELECT cell, trx, foo, bar FROM tchdrop'
db.execute(query)
川水往事 2024-10-28 08:21:23

该库将指定的值 ("cell", "trx") 替换为其引用的 SQL 等效值,因此您得到的是 SELECT "cell", "trx" FROM tchdrop 。结果是正确的。

使用 ? 语法无法实现您想要实现的目标。相反,您自己更换字符串。您可以使用正则表达式(例如 ^[a-zA-Z_]$)检查列名称以提高安全性。

例如:

columns = ",".join(("cell", "trx"))
db.execute("SELECT %s FROM tchdrop" % columns).fetchall()

The library replaces the specified values ("cell", "trx") with their quoted SQL equivalent, so what you get is SELECT "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:

columns = ",".join(("cell", "trx"))
db.execute("SELECT %s FROM tchdrop" % columns).fetchall()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文