projectEli/Database/update.py

78 lines
2.1 KiB
Python

import sqlite3
import csv
import os
# 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" # Change this to your reloading CSV file name
csv_file_ammo = "ammo.csv" # Change this to your new_table CSV file name
# 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)
# Define the table schema for reloading
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS reloading (
id INTEGER PRIMARY KEY AUTOINCREMENT,
type TEXT,
name TEXT,
rarity INTEGER,
weight REAL,
width INTEGER,
height INTEGER,
stack INTEGER,
value INTEGER
)
"""
)
# Define the table schema for new_table
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS ammo (
id INTEGER PRIMARY KEY AUTOINCREMENT,
type TEXT,
name TEXT,
rarity INTEGER,
weight REAL,
width INTEGER,
height INTEGER,
stack INTEGER,
value INTEGER,
gunpowder INTEGER
)
"""
)
# Function to load data from a CSV file into a table
def load_csv_data(csv_path, table_name, cursor):
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 new_table CSV file into the new_table table
load_csv_data(csv_path_ammo, "ammo", cursor)
# Commit the changes and close the connection
conn.commit()
conn.close()