projectEli/Database/importData.py

74 lines
2.5 KiB
Python

import csv
import os
import sqlite3
# Connect to the SQLite database
conn = sqlite3.connect("items.db")
cursor = conn.cursor()
# Define the directory where the CSV files are located
csv_directory = "data" # Change this to your directory path
# Define the CSV file names
csv_file_reloading = "reloading.csv"
csv_file_ammo = "ammo.csv"
csv_file_craft = "craft.csv"
# Build the full paths to the CSV files
csv_path_reloading = os.path.join(csv_directory, csv_file_reloading)
csv_path_ammo = os.path.join(csv_directory, csv_file_ammo)
csv_path_craft = os.path.join(csv_directory, csv_file_craft)
# Define the starting ID values for each table
starting_id_reloading = 20000
starting_id_ammo = 10000
starting_id_craft = 30000
# Set the starting ID values for each table using INSERT statements
cursor.execute(f"INSERT INTO reloading (id) VALUES ({starting_id_reloading})")
cursor.execute(f"INSERT INTO ammo (id) VALUES ({starting_id_ammo})")
cursor.execute(f"INSERT INTO craft (id) VALUES ({starting_id_craft})")
# Reset the ID sequences for all tables
cursor.execute("DELETE FROM SQLITE_SEQUENCE")
cursor.execute(
f"INSERT INTO SQLITE_SEQUENCE (name, seq) VALUES ('reloading', {starting_id_reloading})"
)
cursor.execute(
f"INSERT INTO SQLITE_SEQUENCE (name, seq) VALUES ('ammo', {starting_id_ammo})"
)
cursor.execute(
f"INSERT INTO SQLITE_SEQUENCE (name, seq) VALUES ('craft', {starting_id_craft})"
)
# Function to load data from a CSV file into a table
def load_csv_data(csv_path, table_name, cursor):
# Delete existing data in the table
delete_query = f"DELETE FROM {table_name}"
cursor.execute(delete_query)
with open(csv_path, newline="") as csvfile:
csv_reader = csv.reader(csvfile)
next(csv_reader) # Skip the header row if it exists in the CSV
for row in csv_reader:
# Exclude the first column (id) from the row
values = row[1:]
placeholders = ", ".join(["?"] * len(values))
insert_query = f"INSERT INTO {table_name} VALUES (NULL, {placeholders})"
cursor.execute(insert_query, values)
# Load data from the reloading CSV file into the reloading table
load_csv_data(csv_path_reloading, "reloading", cursor)
# Load data from the ammo CSV file into the ammo table
load_csv_data(csv_path_ammo, "ammo", cursor)
# Load data from the ammo CSV file into the ammo table
load_csv_data(csv_path_craft, "craft", cursor)
# Commit the changes and close the connection
conn.commit()
conn.close()