简体   繁体   English

读取 python 中的 csv 文件并将结果插入 MYSQL 数据库

[英]Read a csv file in python and insert the result into a MYSQL database

I have a csv file with the number of people infected by covid19 per country and per day.我有一个 csv 文件,其中包含每个国家和每天感染 covid19 的人数。 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我创建了一个 MYSQL 数据库,一个包含 CSV 文件具有的所有列的表,现在我需要将行插入到数据库中我需要一个 python 代码来完成任务

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()

I think you have to do mydb.commit() all the insert into.我认为你必须做 mydb.commit() 所有插入。

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请参考: Load CSV data into MySQL in Python

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM