python - 我不知道如何在数据库上执行 SUM 函数并将值存储到 python 变量中

标签 python python-3.x sqlite

我正在尝试使用 Python 和 SQLite3 制作费用跟踪器。我已经弄清楚如何输入数据,字段如下: 金额类别(食品、休闲、交通、教育) 描述 购买日期 我正在尝试创建一个方法,这样我就可以获得当月某个类别的所有费用的总和,并将其放入 python 变量中(因为我想进一步处理并创建不同类别的饼图)

我尝试过使用 SELECT SQL 函数,但我不确定如何解决问题

import sqlite3
import datetime
import time

connectdb = sqlite3.connect("Expenses.db")
c = connectdb.cursor()


def create_table():
    c.execute("CREATE TABLE IF NOT EXISTS Expenses (Amount REAL, Category 
TEXT, Description TEXT, DateOfPurchase TEXT)")


# used to input a record
def datain():
    amount = float(input("Please enter the amount of money paid for the 
             expense"))
    Today = str(datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d'))
    category = str(input("Please pick a category from Food, Transport, 
               Leisure, Education"))
    temp = ("Food", "Transport", "Leisure", "Education")
    while not (category in temp):
        category = str(input("Please pick a category from Food, 
        Transport, Leisure, Education"))
    description = str(input("Please describe the expense in a few 
                  words"))
    c.execute("INSERT INTO Expenses (Amount,Category,Description,DateOfPurchase) VALUES (?,?,?,?)",
          (amount, category, description, Today))
    rerun = str(input("Would you like to add another item? (Yes/No)"))
    if (rerun == "Yes"):
        datain()
    else:
        connectdb.commit()
        c.close()
        connectdb.close()

最佳答案

为了编写详细的解决方案,我想我需要查看数据库的架构。但是,我认为您想要实现的目标的要点是:

query = "SELECT SUM(Amount) FROM Expenses WHERE Month = ?;"
c.execute(query, theMonth)
result = c.fetchone()

然后 result 将是您想要创建的 Python 变量。

关于python - 我不知道如何在数据库上执行 SUM 函数并将值存储到 python 变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57256844/

相关文章:

iphone - 将对象存储在数组中

python - 理解 python for 循环中的范围

python - 在 Python 中使用对象的最佳方式?

python - 四次方程求解器的实现不起作用

python - 类中的可订阅对象

字符串语法问题中的Python变量?

python-3.x - Python 3 Pycharm ide 警告

visual-studio-2010 - Sqlite 不在 Visual Studio 数据源选项列表中

python - 检查另一个字符串中的单词列表

具有动态参数的 C# SQLite Insert 函数