如何获得与元组相似的数据?

发布于 2025-02-13 21:38:53 字数 274 浏览 1 评论 0原文

我想从类似于元组的表中选择数据。这意味着我只会得到像元组中喜欢的数据,例如T1,

conn = sqlite3.connect('mydatabase.db')
cur = conn.cursor()
result = cur.execute("SELECT Sum(amount) FROM items WHERE id In 't1' ")
c1 = cur.fetchall()

但我会得到此错误: sqlite3.erationalerror:没有这样的表:T1

I want to select data from a table that similar to a tuple. It mean I get just data that like in my tuple for example t1

conn = sqlite3.connect('mydatabase.db')
cur = conn.cursor()
result = cur.execute("SELECT Sum(amount) FROM items WHERE id In 't1' ")
c1 = cur.fetchall()

But I get this error:
sqlite3.OperationalError: no such table: t1

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

留蓝 2025-02-20 21:38:53

您需要从表格中选择一个列。

从ID中的项目中选择SUM(量)(从TableName中选择COL1)

如果要获得匹配多个列的值,则内部选择应结合那些列。

从id中的项目中选择“ sum(量)

You need to select a column from the table.

SELECT Sum(amount) From items Where Id In (Select Col1 from TableName)

If you want to get values that match multiple columns, then the inner select should union those columns.

SELECT Sum(amount) From items Where Id In (Select Col1 from TableName Union Select Col2 from TableName)

一身骄傲 2025-02-20 21:38:53

这里的想法是创建一个具有足够的绑定替换变量的查询,该变量等于元组中的元素数量。
为此,我们需要复制binds

请参阅下面的代码和参考

import sqlite3
var_tuple=(1,2,3)
#  Connect
con = sqlite3.connect(r"C:\path\testdb.db")
replace_var= '?'
replace_var= ', '.join(replace_var for _ in var_tuple)
query= 'select * from table_1 where c2 in (%s)' % replace_var
print (query)
#  cursor
cur = con.cursor()
for row in cur.execute(query,var_tuple):
    print(row)
con.close()

The idea here is to create a query with enough bind replace variables which are equal to the number of elements in the tuple.
For that we need to replicate binds ?.

Refer below code and reference.

import sqlite3
var_tuple=(1,2,3)
#  Connect
con = sqlite3.connect(r"C:\path\testdb.db")
replace_var= '?'
replace_var= ', '.join(replace_var for _ in var_tuple)
query= 'select * from table_1 where c2 in (%s)' % replace_var
print (query)
#  cursor
cur = con.cursor()
for row in cur.execute(query,var_tuple):
    print(row)
con.close()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文