简体   繁体   中英

I can't figure out how to perform the SUM function on a DB and store the value into a python variable

I'm trying to make an expense tracker with Python and SQLite3. I've figured out how to input data and the fields are as follows: Amount Category(Food, Leisure, Transport, Education) Description DateOfPurchase I'm trying to create a method so I can get the sum of all the expenses of a certain category in the month and put it into a python variable (because I want to further process and create a pie chart of the different categories)

I've tried working with the SELECT SQL function but I'm not sure how to go about solving the problem

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()

In order to write a detailed solution, I think I'd need to see the schema for your database. However, I think the gist of what you're trying to achieve is something like:

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

And then result will be the Python variable you wanted to create.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM