CSV to MySQL is a simple Python utility that allows you to import data from a CSV file into a MySQL database. This tool checks if the specified database exists and creates it if it doesn't, then creates a table and imports the data from the CSV file.
- Connect to MySQL database
- Check and create database if it doesn't exist
- Create table based on CSV header
- Import CSV data into MySQL table
- Python 3.x
- MySQL server
mysql-connector-python
library
-
Clone the repository:
git clone https://github.com/COMMANDO2406/CSVtoMySQL.git cd CSVtoMySQL
-
Install the required Python packages:
pip install mysql-connector-python
-
Create a
config.py
file:# config.py host = 'your_mysql_host' user = 'your_mysql_user' password = 'your_mysql_password'
-
Prepare your CSV file: Ensure you have a CSV file named
main.csv
in the same directory as the script. The CSV file should have a header row with column names matching the ones you will specify in the script.
-
Run the script:
python csv_to_mysql.py
-
Enter the required information when prompted:
- Database name: Enter the name of the database you want to use. If it doesn't exist, it will be created.
- Table name: Enter the name of the table where the data will be imported.
- Column names: Enter the column names separated by commas. These should match the columns in your CSV file.
Here is an example of how to use the script:
-
Prepare your CSV file (
main.csv
):name,age,city Alice,30,New York Bob,25,Los Angeles
-
Run the script:
python csv_to_mysql.py
-
Enter the following when prompted:
Enter database name: my_database Enter table name: people Enter column names (Separated by commas): name,age,city
-
The script will output:
Connected successfully Database 'my_database' created successfully Data imported successfully.