import os
import sqlite3
import pandas as pd
# Use the current folder where the script is located
folder_path = os.path.dirname(os.path.abspath(__file__))
database_path = os.path.join(folder_path, 'database.db') # Database file in the same folder
# Connect to the SQLite database (or create it if it doesn't exist)
conn = sqlite3.connect(database_path)
cursor = conn.cursor()
# Function to import CSV to SQLite
def import_csv_to_sqlite(file_path, conn):
# Extract table name from the file name (without extension)
table_name = os.path.splitext(os.path.basename(file_path))[0]
# Load CSV into a Pandas DataFrame
try:
df = pd.read_csv(file_path)
# Write the DataFrame to SQLite
df.to_sql(table_name, conn, if_exists='replace', index=False)
print(f"Imported {table_name} successfully!")
except Exception as e:
print(f"Error importing {file_path}: {e}")
# Loop through all CSV files in the folder
for file_name in os.listdir(folder_path):
if file_name.endswith('.csv'):
file_path = os.path.join(folder_path, file_name)
import_csv_to_sqlite(file_path, conn)
# Close the database connection
conn.close()
print(f"All CSV files in '{folder_path}' have been imported into the SQLite database: {database_path}")