gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 20:34:29 25 4
gpt4 key购买 nike

我正在尝试使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com