Spaces:
Running
Running
Create database.py
Browse files- database.py +43 -0
database.py
ADDED
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sqlalchemy import (
|
2 |
+
create_engine,
|
3 |
+
MetaData,
|
4 |
+
Table,
|
5 |
+
Column,
|
6 |
+
String,
|
7 |
+
Integer,
|
8 |
+
Float,
|
9 |
+
insert,
|
10 |
+
)
|
11 |
+
|
12 |
+
# Initialize in-memory SQLite database
|
13 |
+
engine = create_engine("sqlite:///:memory:")
|
14 |
+
metadata_obj = MetaData()
|
15 |
+
|
16 |
+
# Define 'receipts' table
|
17 |
+
receipts = Table(
|
18 |
+
"receipts",
|
19 |
+
metadata_obj,
|
20 |
+
Column("receipt_id", Integer, primary_key=True),
|
21 |
+
Column("customer_name", String(16), primary_key=True),
|
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
|
30 |
+
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 |
+
rows = [
|
36 |
+
{"receipt_id": 1, "customer_name": "Alan Payne", "price": 12.06, "tip": 1.20},
|
37 |
+
{"receipt_id": 2, "customer_name": "Alex Mason", "price": 23.86, "tip": 0.24},
|
38 |
+
{"receipt_id": 3, "customer_name": "Woodrow Wilson", "price": 53.43, "tip": 5.43},
|
39 |
+
{"receipt_id": 4, "customer_name": "Margaret James", "price": 21.11, "tip": 1.00},
|
40 |
+
]
|
41 |
+
|
42 |
+
# Populate the database
|
43 |
+
insert_rows_into_table(rows, receipts)
|