Import CSV file data into MySQL table using Python

Posted by

In this tutorial, we will learn to import CSV file data into a MySQL table using Python. We will read the CSV file, connect with the database and load the CSV data in the MySQL table. You will be required below package for connecting the database.

Steps to Import CSV file data into MySQL table using Python:

  1. Import the mysql.connect and csv module.
  2. Connect with the database and select the database using mysql.connect method. Please do not forget to change the database user, password, host, and database name.
  3. To execute queries on the database table, we create a cursor object.
  4. Open the CSV file in read mode using the open() function.
  5. Read the CSV file data using csv.reader method.
  6. Skip header next method.
  7. Run loop to read CSV data row-wise.
  8. Run and execute the insert query to insert data in the MySQL table. Please change the table name and field name. This will be changed by CSV headers and table fields name.
  9. Commit the query and close the cursor.
  10. Log in to your database, select table, and verify your inserted data from CSV file data.

Also, the code is committed on GitHub. You can check it out there.

Leave a Reply

Your email address will not be published. Required fields are marked *