-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.py
More file actions
41 lines (36 loc) · 1.15 KB
/
Copy pathdb.py
File metadata and controls
41 lines (36 loc) · 1.15 KB
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
import sqlite3
def get_connection():
con = sqlite3.connect("workouts.db")
con.row_factory = sqlite3.Row # rows accessible by column name, not position
return con
def init_db():
con = get_connection()
cur = con.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS workouts(id INTEGER PRIMARY KEY, sport TEXT, distance_km REAL, duration_min REAL)")
con.commit()
con.close()
def get_all_workouts():
con = get_connection()
cur = con.cursor()
cur.execute("SELECT * FROM workouts")
rows = cur.fetchall()
con.close()
return [dict(r) for r in rows]
def add_workout(data):
con = get_connection()
cur = con.cursor()
cur.execute(
"INSERT INTO workouts (sport, distance_km, duration_min) VALUES (?, ?, ?)",
(data["sport"], data.get("distance_km"), data.get("duration_min"))
)
con.commit()
new_id = cur.lastrowid
con.close()
return {"id": new_id, **data}
def get_workout_by_id(workout_id):
con = get_connection()
cur = con.cursor()
cur.execute("SELECT * FROM workouts WHERE id = ?", (workout_id,))
row = cur.fetchone()
con.close()
return dict(row) if row else None