Spaces:
Sleeping
Sleeping
File size: 1,356 Bytes
037ba4c 3c77808 037ba4c 716c2a2 037ba4c 716c2a2 037ba4c 716c2a2 037ba4c 716c2a2 |
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 |
from sqlalchemy import (
create_engine,
MetaData,
Table,
Column,
String,
Integer,
Float,
insert,
text,
)
# Use a persistent SQLite database file
engine = create_engine("sqlite:///database.db")
metadata_obj = MetaData()
# Define 'receipts' table
receipts = Table(
"receipts",
metadata_obj,
Column("receipt_id", Integer, primary_key=True),
Column("customer_name", String(16)),
Column("price", Float),
Column("tip", Float),
)
# Create the table if it doesn't exist
metadata_obj.create_all(engine)
# Function to insert rows into the table
def insert_rows_into_table(rows, table):
with engine.begin() as connection:
connection.execute(insert(table), rows)
# Insert sample data if table is empty
with engine.connect() as conn:
result = conn.execute(text("SELECT COUNT(*) FROM receipts"))
count = result.scalar()
if count == 0:
rows = [
{"receipt_id": 1, "customer_name": "Alan Payne", "price": 12.06, "tip": 1.20},
{"receipt_id": 2, "customer_name": "Alex Mason", "price": 23.86, "tip": 0.24},
{"receipt_id": 3, "customer_name": "Woodrow Wilson", "price": 53.43, "tip": 5.43},
{"receipt_id": 4, "customer_name": "Margaret James", "price": 21.11, "tip": 1.00},
]
insert_rows_into_table(rows, receipts)
|