|
1 |
| -import tkinter as tk |
2 |
| -from tkinter import messagebox |
3 |
| -from tkinter import filedialog |
| 1 | +import sys |
| 2 | +from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QLineEdit, QPushButton, QFileDialog, QMessageBox, QVBoxLayout, QHBoxLayout |
4 | 3 | import mysql.connector
|
5 | 4 | import csv
|
6 | 5 | from config import host, user, password
|
7 | 6 |
|
8 |
| -def connect_to_database(database_name, table_name, header, csv_file): |
9 |
| - try: |
10 |
| - con = mysql.connector.connect( |
11 |
| - host=host, |
12 |
| - user=user, |
13 |
| - password=password |
14 |
| - ) |
15 |
| - |
16 |
| - cur = con.cursor() |
17 |
| - |
18 |
| - if con.is_connected(): |
19 |
| - print("Connected successfully") |
20 |
| - else: |
21 |
| - print("Not connected") |
22 |
| - |
23 |
| - # Check if the database exists and create it if it doesn't |
24 |
| - cur.execute(f"SHOW DATABASES LIKE '{database_name}'") |
25 |
| - result = cur.fetchone() |
26 |
| - |
27 |
| - if not result: |
28 |
| - cur.execute(f"CREATE DATABASE {database_name}") |
29 |
| - print(f"Database '{database_name}' created successfully") |
30 |
| - else: |
31 |
| - print(f"Database '{database_name}' already exists") |
32 |
| - |
33 |
| - # Connect to the newly created or existing database |
34 |
| - con.database = database_name |
35 |
| - |
36 |
| - columns = [f"{col.strip()} varchar(255)" for col in header.split(",")] |
37 |
| - |
38 |
| - # this is a create query and it works by using the join funtion on the column names so that they are seperated by commas |
39 |
| - # over here the query is required to be in uppercase as during testing the code would throw an error if it wasn't |
40 |
| - create_table_query = f"CREATE TABLE IF NOT EXISTS {table_name} ({', '.join(columns)})" |
41 |
| - cur.execute(create_table_query) |
42 |
| - |
43 |
| - with open(csv_file, "r") as file: |
44 |
| - reader = csv.reader(file) |
45 |
| - # this is the reader object from the csv module |
46 |
| - next(reader) |
47 |
| - |
48 |
| - for row in reader: |
49 |
| - insert_query = f"INSERT INTO {table_name} ({', '.join(header.split(','))}) values ({', '.join(['%s'] * len(row))})" |
50 |
| - # this is the query creation part of the code, it works by using a formated string to insert the variables |
51 |
| - # the %s is used instead of a variable as it is required for mysql |
52 |
| - # and it dosent work if the variable is directly put into the formatted str. |
53 |
| - values = tuple(row) |
54 |
| - cur.execute(insert_query, values) |
55 |
| - # the cur.execute function requires the query with the %s and a tuple contaning the varaibles in the above format |
56 |
| - |
57 |
| - con.commit() |
58 |
| - con.close() |
59 |
| - messagebox.showinfo("Success", "Data imported successfully.") |
60 |
| - except mysql.connector.Error as err: |
61 |
| - messagebox.showerror("Error", f"Error: {err}") |
62 |
| - |
63 |
| -def browse_file(): |
64 |
| - file_path = filedialog.askopenfilename(filetypes=[("CSV files", "*.csv")]) |
65 |
| - csv_path_entry.delete(0, tk.END) |
66 |
| - csv_path_entry.insert(0, file_path) |
67 |
| - |
68 |
| -app = tk.Tk() |
69 |
| -app.title("CSV to MySQL Importer") |
70 |
| - |
71 |
| -tk.Label(app, text="Database Name:").grid(row=0, column=0, padx=10, pady=10) |
72 |
| -db_name_entry = tk.Entry(app) |
73 |
| -db_name_entry.grid(row=0, column=1, padx=10, pady=10) |
74 |
| - |
75 |
| -tk.Label(app, text="Table Name:").grid(row=1, column=0, padx=10, pady=10) |
76 |
| -table_name_entry = tk.Entry(app) |
77 |
| -table_name_entry.grid(row=1, column=1, padx=10, pady=10) |
78 |
| - |
79 |
| -tk.Label(app, text="Column Names (comma separated):").grid(row=2, column=0, padx=10, pady=10) |
80 |
| -column_names_entry = tk.Entry(app) |
81 |
| -column_names_entry.grid(row=2, column=1, padx=10, pady=10) |
82 |
| - |
83 |
| -tk.Label(app, text="CSV File Path:").grid(row=3, column=0, padx=10, pady=10) |
84 |
| -csv_path_entry = tk.Entry(app) |
85 |
| -csv_path_entry.grid(row=3, column=1, padx=10, pady=10) |
86 |
| -tk.Button(app, text="Browse", command=browse_file).grid(row=3, column=2, padx=10, pady=10) |
87 |
| - |
88 |
| -def on_import(): |
89 |
| - database_name = db_name_entry.get() |
90 |
| - table_name = table_name_entry.get() |
91 |
| - column_names = column_names_entry.get() |
92 |
| - csv_file_path = csv_path_entry.get() |
93 |
| - |
94 |
| - if not database_name or not table_name or not column_names or not csv_file_path: |
95 |
| - messagebox.showerror("Error", "All fields are required") |
96 |
| - return |
97 |
| - |
98 |
| - connect_to_database(database_name, table_name, column_names, csv_file_path) |
99 |
| - |
100 |
| -tk.Button(app, text="Import", command=on_import).grid(row=4, column=0, columnspan=3, padx=10, pady=10) |
101 |
| - |
102 |
| -app.mainloop() |
| 7 | +class CsvToMysqlApp(QWidget): |
| 8 | + def __init__(self): |
| 9 | + super().__init__() |
| 10 | + |
| 11 | + self.initUI() |
| 12 | + |
| 13 | + def initUI(self): |
| 14 | + self.setWindowTitle('CSV to MySQL Importer') |
| 15 | + |
| 16 | + # Database Name |
| 17 | + db_label = QLabel('Database Name:') |
| 18 | + self.db_name = QLineEdit() |
| 19 | + |
| 20 | + # Table Name |
| 21 | + table_label = QLabel('Table Name:') |
| 22 | + self.table_name = QLineEdit() |
| 23 | + |
| 24 | + # Column Names |
| 25 | + columns_label = QLabel('Column Names (comma separated):') |
| 26 | + self.columns = QLineEdit() |
| 27 | + |
| 28 | + # CSV File Path |
| 29 | + csv_label = QLabel('CSV File Path:') |
| 30 | + self.csv_path = QLineEdit() |
| 31 | + browse_button = QPushButton('Browse') |
| 32 | + browse_button.clicked.connect(self.browse_file) |
| 33 | + |
| 34 | + # Import Button |
| 35 | + import_button = QPushButton('Import') |
| 36 | + import_button.clicked.connect(self.import_data) |
| 37 | + |
| 38 | + # Layout |
| 39 | + layout = QVBoxLayout() |
| 40 | + layout.addWidget(db_label) |
| 41 | + layout.addWidget(self.db_name) |
| 42 | + layout.addWidget(table_label) |
| 43 | + layout.addWidget(self.table_name) |
| 44 | + layout.addWidget(columns_label) |
| 45 | + layout.addWidget(self.columns) |
| 46 | + layout.addWidget(csv_label) |
| 47 | + |
| 48 | + csv_layout = QHBoxLayout() |
| 49 | + csv_layout.addWidget(self.csv_path) |
| 50 | + csv_layout.addWidget(browse_button) |
| 51 | + layout.addLayout(csv_layout) |
| 52 | + |
| 53 | + layout.addWidget(import_button) |
| 54 | + |
| 55 | + self.setLayout(layout) |
| 56 | + |
| 57 | + def browse_file(self): |
| 58 | + file_path, _ = QFileDialog.getOpenFileName(self, "Open CSV File", "", "CSV Files (*.csv)") |
| 59 | + if file_path: |
| 60 | + self.csv_path.setText(file_path) |
| 61 | + |
| 62 | + def import_data(self): |
| 63 | + database_name = self.db_name.text() |
| 64 | + table_name = self.table_name.text() |
| 65 | + column_names = self.columns.text() |
| 66 | + csv_file_path = self.csv_path.text() |
| 67 | + |
| 68 | + if not database_name or not table_name or not column_names or not csv_file_path: |
| 69 | + QMessageBox.warning(self, 'Error', 'All fields are required') |
| 70 | + return |
| 71 | + |
| 72 | + try: |
| 73 | + con = mysql.connector.connect( |
| 74 | + host=host, |
| 75 | + user=user, |
| 76 | + password=password |
| 77 | + ) |
| 78 | + |
| 79 | + cur = con.cursor() |
| 80 | + |
| 81 | + if con.is_connected(): |
| 82 | + print("Connected successfully") |
| 83 | + else: |
| 84 | + print("Not connected") |
| 85 | + |
| 86 | + # Check if the database exists and create it if it doesn't |
| 87 | + cur.execute(f"SHOW DATABASES LIKE '{database_name}'") |
| 88 | + result = cur.fetchone() |
| 89 | + |
| 90 | + if not result: |
| 91 | + cur.execute(f"CREATE DATABASE {database_name}") |
| 92 | + print(f"Database '{database_name}' created successfully") |
| 93 | + else: |
| 94 | + print(f"Database '{database_name}' already exists") |
| 95 | + |
| 96 | + # Connect to the newly created or existing database |
| 97 | + con.database = database_name |
| 98 | + |
| 99 | + columns = [f"{col.strip()} varchar(255)" for col in column_names.split(",")] |
| 100 | + create_table_query = f"CREATE TABLE IF NOT EXISTS {table_name} ({', '.join(columns)})" |
| 101 | + cur.execute(create_table_query) |
| 102 | + |
| 103 | + with open(csv_file_path, "r") as file: |
| 104 | + reader = csv.reader(file) |
| 105 | + next(reader) |
| 106 | + |
| 107 | + for row in reader: |
| 108 | + insert_query = f"INSERT INTO {table_name} ({', '.join(column_names.split(','))}) values ({', '.join(['%s'] * len(row))})" |
| 109 | + values = tuple(row) |
| 110 | + cur.execute(insert_query, values) |
| 111 | + |
| 112 | + con.commit() |
| 113 | + con.close() |
| 114 | + QMessageBox.information(self, 'Success', 'Data imported successfully.') |
| 115 | + except mysql.connector.Error as err: |
| 116 | + QMessageBox.critical(self, 'Error', f"Error: {err}") |
| 117 | + |
| 118 | +if __name__ == '__main__': |
| 119 | + app = QApplication(sys.argv) |
| 120 | + ex = CsvToMysqlApp() |
| 121 | + ex.show() |
| 122 | + sys.exit(app.exec_()) |
0 commit comments