11import sqlite3
2-
3- # Connect to the database
2+ import csv
3+ # Connect to the database
44conn = sqlite3 .connect ("expenses.db" )
55cursor = conn .cursor ()
66
7- # Define SQL statements
87create_table_sql = """CREATE TABLE IF NOT EXISTS expenses (id INTEGER PRIMARY KEY AUTOINCREMENT, date TEXT, description TEXT, amount REAL)"""
98insert_expense_sql = "INSERT INTO expenses (date, description, amount) VALUES (?, ?, ?)"
109select_expenses_sql = "SELECT * FROM expenses ORDER BY date;"
1110delete_expense_by_id_sql = "DELETE FROM expenses WHERE id=?"
1211update_expense_by_id_sql = "UPDATE expenses SET description=? WHERE id=?"
1312
1413# Check if the database exists, create it if not
15- if not conn .execute (
16- "SELECT name FROM sqlite_master WHERE type='table' AND name='expenses';"
17- ).fetchone ():
14+ if not conn .execute ("SELECT name FROM sqlite_master WHERE type='table' AND name='expenses';" ).fetchone ():
1815 cursor .execute (create_table_sql )
1916 conn .commit ()
17+
18+
19+
20+ # Define SQL statements
21+
2022
2123
2224def add_expense ():
2325 global cursor
2426
2527 # Get input from user
2628 print ("Enter date (YYYY-MM-DD): " )
27- date = input ().split ()[0 ] + "-01"
29+ date = input ().split ()[0 ]
2830 print ("Enter description: " )
2931 description = input ()
3032 print ("Enter amount: " )
@@ -40,34 +42,39 @@ def add_expense():
4042
4143def delete_expense ():
4244 global cursor
45+ if is_empty ()== True :
46+ print ("No expenses recorded yet." )
47+ else :
4348
4449 # Get ID from user
45- print ("Enter ID to delete: " )
46- id = int (input ())
50+ print ("Enter ID to delete: " )
51+ id = int (input ())
4752
48- try :
49- cursor .execute (delete_expense_by_id_sql , (id ,))
50- conn .commit ()
51- print ("Expense deleted successfully." )
52- except Exception as e :
53- print ("Error deleting expense: {}" .format (e ))
53+ try :
54+ cursor .execute (delete_expense_by_id_sql , (id ,))
55+ conn .commit ()
56+ print ("Expense deleted successfully." )
57+ except Exception as e :
58+ print ("Error deleting expense: {}" .format (e ))
5459
5560
5661def update_expense ():
5762 global cursor
58-
63+ if is_empty ()== True :
64+ print ("No expenses recorded yet." )
65+ else :
5966 # Get ID and new description from user
60- print ("Enter ID to update: " )
61- id = int (input ())
62- print ("Enter new description: " )
63- description = input ()
67+ print ("Enter ID to update: " )
68+ id = int (input ())
69+ print ("Enter new description: " )
70+ description = input ()
6471
65- try :
66- cursor .execute (update_expense_by_id_sql , (description , id ))
67- conn .commit ()
68- print ("Expense updated successfully." )
69- except Exception as e :
70- print ("Error updating expense: {}" .format (e ))
72+ try :
73+ cursor .execute (update_expense_by_id_sql , (description , id ))
74+ conn .commit ()
75+ print ("Expense updated successfully." )
76+ except Exception as e :
77+ print ("Error updating expense: {}" .format (e ))
7178
7279
7380def view_expenses ():
@@ -88,16 +95,42 @@ def total_expenses():
8895 total = conn .execute ("SELECT SUM(amount) FROM expenses;" ).fetchone ()[0 ]
8996 print (f"Total expenses: { total } $" )
9097
98+ #defining function for exporting to csv
99+ def print_csv ():
100+ #opening csv file
101+ with open ('expense.csv' ,"w" ) as csvfile :
102+ #
103+ csvwriter = csv .writer (csvfile )
104+ csvwriter .writerow (["ID" ,"DATE" ,"Desc" ,"description" ]) # To Define heading of rows of csv
105+ csvwriter .writerows (cursor )
106+ expenses = conn .execute (select_expenses_sql ).fetchall ()
107+ for i in expenses :
108+ print (i )
109+ csvwriter .writerow (i ) #writing querys to csv
110+ total = conn .execute ("SELECT SUM(amount) FROM expenses;" ).fetchone ()[0 ] # For total Expenses
111+ csvwriter .writerow (["" ,"" ,"Total Expenses:" ,total ]) # Printing to CSV
112+
113+
114+
115+ #defined this funtion to check is database is empty or not
116+ def is_empty ():
117+ if conn .execute (select_expenses_sql ).fetchall ()== []:
118+
119+ return True
120+ else :
121+ return False
91122
92123def main_menu ():
124+ #conn=db_init()
93125 while True :
94126 print ("\n Expense Tracker Menu:" )
95127 print ("1. Add Expense" )
96128 print ("2. View Expenses" )
97129 print ("3. Total Expenses" )
98130 print ("4. Delete Expense" )
99131 print ("5. Update Expense Description" )
100- print ("6. Quit" )
132+ print ("6. Export Expense" )
133+ print ("7. Quit" )
101134
102135 choice = input ("Enter your choice (1-6): " )
103136
@@ -112,12 +145,16 @@ def main_menu():
112145 elif choice == "5" :
113146 update_expense ()
114147 elif choice == "6" :
115- break
148+ print_csv ()
149+ elif choice == "7" :
150+ is_empty ()
116151 else :
152+
117153 print ("Invalid choice. Please try again." )
118154
119155
120156if __name__ == "__main__" :
121157 main_menu ()
122158
159+
123160conn .close ()
0 commit comments