Repository navigation
Expand file tree
/
Copy pathdata_loading.py
More file actions
63 lines (51 loc) · 1.61 KB
/
Copy pathdata_loading.py
File metadata and controls
63 lines (51 loc) · 1.61 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import json
import sqlite3
import os
transformed_data_source = "transformed_data.json"
database_name = "pokemon.db"
if not os.path.exists(transformed_data_source):
raise FileNotFoundError(
f"'{transformed_data_source}' not found. Run 'data_transformation.py' to generate it"
)
def load_data_from_json(filename):
with open(filename, "r") as file:
return json.load(file)
def load_data_into_sqlite(data, db_filename):
conn = sqlite3.connect(db_filename)
cursor = conn.cursor()
try:
cursor.execute(
"""CREATE TABLE IF NOT EXISTS pokemon_data (
id INTEGER PRIMARY KEY,
name TEXT,
height REAL,
weight REAL,
bmi REAL
)"""
)
for pokemon in data:
cursor.execute(
"""INSERT INTO pokemon_data (id, name, height, weight, bmi)
VALUES (?, ?, ?, ?, ?)
""",
(
pokemon["id"],
pokemon["pokemon"]["name"],
pokemon["height"],
pokemon["weight"],
pokemon["bmi"],
),
)
conn.commit()
print(
f"Data loaded into '{database_name}' SQLite database successfully!"
)
except Exception as e:
print("Error:", str(e))
finally:
conn.close()
try:
pokemon_data = load_data_from_json(transformed_data_source)
load_data_into_sqlite(pokemon_data, database_name)
except Exception as e:
print("Error:", str(e))