-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDB.py
106 lines (82 loc) · 3.16 KB
/
DB.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import sqlite3
import yfinance as yf
class DB():
def create_db():
conn = sqlite3.connect('stocks.db')
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS favorite_stocks (
ticker_symbol TEXT PRIMARY KEY,
stock_name TEXT,
amount INTEGER
)
''')
conn.commit()
conn.close()
def add_favorite_stock(ticker_symbol, stock_name, amount):
conn = sqlite3.connect('stocks.db')
cursor = conn.cursor()
success = 0
try:
cursor.execute('''
SELECT amount FROM favorite_stocks WHERE ticker_symbol = ?
''', (ticker_symbol,))
row = cursor.fetchone()
if row:
current_amount = row[0]
new_amount = current_amount + amount
cursor.execute('''
UPDATE favorite_stocks
SET amount = ?, stock_name = ?
WHERE ticker_symbol = ?
''', (new_amount, stock_name, ticker_symbol))
else:
cursor.execute('''
INSERT INTO favorite_stocks (ticker_symbol, stock_name, amount)
VALUES (?, ?, ?)
''', (ticker_symbol, stock_name, amount))
success = 1
conn.commit()
except Exception as e:
print(f"An error occurred while adding {ticker_symbol}: {e}")
finally:
conn.close()
return success
def remove_favorite_stock(ticker_symbol, amount):
conn = sqlite3.connect('stocks.db')
cursor = conn.cursor()
success = 0
try:
cursor.execute('''
SELECT amount FROM favorite_stocks WHERE ticker_symbol = ?
''', (ticker_symbol,))
row = cursor.fetchone()
if row:
current_amount = row[0]
new_amount = current_amount - amount
if new_amount > 0:
cursor.execute('''
UPDATE favorite_stocks SET amount = ? WHERE ticker_symbol = ?
''', (new_amount, ticker_symbol))
print(f"{ticker_symbol} updated successfully. New amount: {new_amount}")
else:
cursor.execute('''
DELETE FROM favorite_stocks WHERE ticker_symbol = ?
''', (ticker_symbol,))
print(f"{ticker_symbol} removed successfully as the amount reached 0.")
success = 1
else:
print(f"{ticker_symbol} not found in favorite_stocks.")
conn.commit()
except Exception as e:
print(f"An error occurred while processing {ticker_symbol}: {e}")
finally:
conn.close()
return success
def get_favorite_stocks():
conn = sqlite3.connect('stocks.db')
cursor = conn.cursor()
cursor.execute('SELECT ticker_symbol, amount FROM favorite_stocks')
favorites = cursor.fetchall()
conn.close()
return favorites