请问我如何总结 sqlite3 表行中的所有整数元素



我想使用 sqlite3 数据库表中的用户数据计算行元素的总和

我使用 cursor.fetchall(( 获取数据库表中的金额行,并尝试使用 for 循环对表的元素求和,但出现错误

db = sqlite3.connect('my.db')
cursor = db.cursor()
cursor.execute('SELECT amount FROM expenses')
result = cursor.fetchall()
c = 0
for x in result:
    c += x
print(c)

我得到了类型错误: += 不支持的操作数类型:"int"和"tuple"我期望得到金额的总和

我知道sqlite3 SUM命令。但是我想学习如何使用 Tkinter

使用 Python 内置的 sum() (doc( 函数:

c = sum(i[0] for i in result)

我所知,cursor.fetchall((返回一个元组(就像你的错误告诉你的那样(,这意味着你对sql查询的所有选择都将被推送到该元组中。

例如,如果要选择多个列:

'SELECT amount, tax, date FROM expenses' 

您将像这样检索元组:

(amount, tax, date)

此元组为每一行提供。在您的案例中,结果是一个包含所有行的数组,其中每一行本身就是一个元组,其中只有数量。

长话短说,您需要将结果重建为具有列表理解的列表,例如:

db = sqlite3.connect('test.db')
cursor = db.cursor()
cursor.execute('SELECT amount FROM expenses')
result = cursor.fetchall()
result = [amount[0] for amount in result] # Rebuild your result array to contain 
                                          # single values instead of tuples
c = 0
for x in result:
    c += x
print(c)

另一种解决方案是:

db = sqlite3.connect('test.db')
cursor = db.cursor()
cursor.execute('SELECT amount FROM expenses')
result = cursor.fetchall()
c = 0
for x in result:
    c += x[0] # This will retrieve the 0th element from the tuple, which is the amount
print(c)

相关内容

最新更新