-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathload_db.py
77 lines (72 loc) · 2.2 KB
/
load_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
import pandas as pd
import sqlalchemy as sa
import sqlite3
import os
db_path = "./db/lesson.db"
if os.path.exists(db_path):
answer = input("The database exists. Do you want to recreate it (y/n)?")
if answer.lower() != 'y':
exit(0)
os.remove(db_path)
with sqlite3.connect("./db/lesson.db",isolation_level='IMMEDIATE') as conn:
conn = sqlite3.connect("./db/lesson.db",isolation_level='IMMEDIATE')
conn.execute("PRAGMA foreign_keys = 1")
cursor = conn.cursor()
# customer_name,contact,street,city,country,postal_code,phone
# Create tables
cursor.execute("""
CREATE TABLE IF NOT EXISTS customers (
customer_id INTEGER PRIMARY KEY,
customer_name TEXT,
contact TEXT,
street TEXT,
city TEXT,
postal_code TEXT,
country TEXT,
phone TEXT
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS employees (
employee_id INTEGER PRIMARY KEY,
first_name TEXT,
last_name TEXT,
phone TEXT
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS products (
product_id INTEGER PRIMARY KEY,
product_name TEXT,
price REAL
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS line_items (
line_item_id INTEGER PRIMARY KEY,
order_id INTEGER,
product_id INTEGER,
quantity INTEGER,
FOREIGN KEY(order_id) REFERENCES orders(order_id),
FOREIGN KEY(product_id) REFERENCES products(product_id)
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER,
employee_id INTEGER,
date TEXT,
FOREIGN KEY(customer_id) REFERENCES customers(customer_id),
FOREIGN KEY(employee_id) REFERENCES employees(employee_id)
)
""")
# Create a database engine
engine = sa.create_engine('sqlite:///db/lesson.db')
tables = ["customers", "employees",
"products", "orders", "line_items"]
for table in tables:
t_name = table.lower()
csv_file = "./csv/" + table + ".csv"
data = pd.read_csv(csv_file, sep=',')
data.to_sql(t_name, engine, if_exists='append', index=False)