Python code to insert CSV data fields to a local Database table using Django

We can use this code to insert the data in a CSV file to a local database table. Just change the table name, database name, and data fields with your respective field name and others.

import mysql.connector
  from mysql.connector import Error
  file = open('file path along with file name and extension')
  csv_reader = csv. reader(file)
  next(csv_reader)
  

  try:
    connection = mysql.connector.connect(host='localhost', database='database name', user='****', password='****')
    for row in csv_reader:
      mySql_insert_query = """INSERT INTO table_name (table data fields name,table data fields name,table data fields name ) VALUES (%s, %s, %s) """
      cursor = connection.cursor()
   
      result = cursor.execute(mySql_insert_query, row)
      connection.commit()
    print("Data Records inserted successfully")
  except mysql.connector.Error as error:
    connection.rollback()
    print("Failed to insert into MySQL table {}".format(error))

  finally:
    if (connection.is_connected()):
      cursor.close()
      connection.close()
      print("MySQL connection is closed")
  return HttpResponse(t)

Leave a comment

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