1

I have a csv file with the number of people infected by covid19 per country and per day. I have created a MYSQL database, a table with all the columns that the CSV file has and now I need to insert the rows into the database I need to have a python code to achieve the task

import pandas as pd
import mysql.connector


mydb = mysql.connector.connect(
  host=
  user="root",
  passwd=
  database="covid19"
)

#Inserting data into the database

mycursor = mydb.cursor()

dataframe = pd.read_csv("total_cases.csv")
print(dataframe)

for row in dataframe:
     print(index)
     mycursor.execute("INSERT INTO covid_per_day_per_country (date, World, 
     Afghanistan, Albania, Algeria, Andorra"))
     mydb.commit()
     cursor.close()

1 Answers1

0

I think you have to do mydb.commit() all the insert into.

Something like this

import csv
import MySQLdb
mydb = mysql.connector.connect(
  host=
  user="root",
  passwd=
  database="covid19"
)
mycursor = mydb.cursor()

dataframe = csv.reader(file('total_cases.csv'))
print(dataframe)

for row in dataframe:
     mycursor.execute('INSERT INTO covid_per_day_per_country (date, World, Afghanistan, Albania, Algeria, Andorra") VALUES("%s", "%s", "%s", "%s", "%s", "%s")', row)
mydb.commit()
cursor.close()

Please refer this: Load CSV data into MySQL in Python

rdas
  • 20,604
  • 6
  • 33
  • 46
Pratik Joshi
  • 389
  • 4
  • 13