presist database
Browse files- database.py +16 -14
database.py
CHANGED
@@ -9,8 +9,8 @@ from sqlalchemy import (
|
|
9 |
insert,
|
10 |
)
|
11 |
|
12 |
-
#
|
13 |
-
engine = create_engine("sqlite
|
14 |
metadata_obj = MetaData()
|
15 |
|
16 |
# Define 'receipts' table
|
@@ -18,12 +18,12 @@ receipts = Table(
|
|
18 |
"receipts",
|
19 |
metadata_obj,
|
20 |
Column("receipt_id", Integer, primary_key=True),
|
21 |
-
Column("customer_name", String(16)
|
22 |
Column("price", Float),
|
23 |
Column("tip", Float),
|
24 |
)
|
25 |
|
26 |
-
# Create the table
|
27 |
metadata_obj.create_all(engine)
|
28 |
|
29 |
# Function to insert rows into the table
|
@@ -31,13 +31,15 @@ def insert_rows_into_table(rows, table):
|
|
31 |
with engine.begin() as connection:
|
32 |
connection.execute(insert(table), rows)
|
33 |
|
34 |
-
# Insert sample data
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
|
|
|
|
|
9 |
insert,
|
10 |
)
|
11 |
|
12 |
+
# Use a persistent SQLite database file
|
13 |
+
engine = create_engine("sqlite:///database.db")
|
14 |
metadata_obj = MetaData()
|
15 |
|
16 |
# Define 'receipts' table
|
|
|
18 |
"receipts",
|
19 |
metadata_obj,
|
20 |
Column("receipt_id", Integer, primary_key=True),
|
21 |
+
Column("customer_name", String(16)),
|
22 |
Column("price", Float),
|
23 |
Column("tip", Float),
|
24 |
)
|
25 |
|
26 |
+
# Create the table if it doesn't exist
|
27 |
metadata_obj.create_all(engine)
|
28 |
|
29 |
# Function to insert rows into the table
|
|
|
31 |
with engine.begin() as connection:
|
32 |
connection.execute(insert(table), rows)
|
33 |
|
34 |
+
# Insert sample data if table is empty
|
35 |
+
with engine.connect() as conn:
|
36 |
+
result = conn.execute(text("SELECT COUNT(*) FROM receipts"))
|
37 |
+
count = result.scalar()
|
38 |
+
if count == 0:
|
39 |
+
rows = [
|
40 |
+
{"receipt_id": 1, "customer_name": "Alan Payne", "price": 12.06, "tip": 1.20},
|
41 |
+
{"receipt_id": 2, "customer_name": "Alex Mason", "price": 23.86, "tip": 0.24},
|
42 |
+
{"receipt_id": 3, "customer_name": "Woodrow Wilson", "price": 53.43, "tip": 5.43},
|
43 |
+
{"receipt_id": 4, "customer_name": "Margaret James", "price": 21.11, "tip": 1.00},
|
44 |
+
]
|
45 |
+
insert_rows_into_table(rows, receipts)
|