-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbook_manager.py
More file actions
55 lines (49 loc) · 2.02 KB
/
book_manager.py
File metadata and controls
55 lines (49 loc) · 2.02 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
import sqlite3
import pandas as pd
import pathlib
# Define the database file in the current root project directory
db_file = pathlib.Path("project.db")
def create_database():
"""Function to create a database. Connecting for the first time
will create a new database file if it doesn't exist yet.
Close the connection after creating the database
to avoid locking the file."""
try:
conn = sqlite3.connect(db_file)
conn.close()
print("Database created successfully.")
except sqlite3.Error as e:
print("Error creating the database:", e)
def create_tables():
"""Function to read and execute SQL statements to create tables"""
try:
with sqlite3.connect(db_file) as conn:
sql_file = pathlib.Path("sql", "create_tables.sql")
with open(sql_file, "r") as file:
sql_script = file.read()
conn.executescript(sql_script)
print("Tables created successfully.")
except sqlite3.Error as e:
print("Error creating tables:", e)
def insert_data_from_csv():
"""Function to use pandas to read data from CSV files (in 'data' folder)
and insert the records into their respective tables."""
try:
author_data_path = pathlib.Path("data", "authors.csv")
book_data_path = pathlib.Path("data", "books.csv")
authors_df = pd.read_csv(author_data_path)
books_df = pd.read_csv(book_data_path)
with sqlite3.connect(db_file) as conn:
# use the pandas DataFrame to_sql() method to insert data
# pass in the table name and the connection
authors_df.to_sql("authors", conn, if_exists="replace", index=False)
books_df.to_sql("books", conn, if_exists="replace", index=False)
print("Data inserted successfully.")
except (sqlite3.Error, pd.errors.EmptyDataError, FileNotFoundError) as e:
print("Error inserting data:", e)
def main():
create_database()
create_tables()
insert_data_from_csv()
if __name__ == "__main__":
main()