Невозможно вставить строки файла CSV в базу данных MYSQL через python - PullRequest
0 голосов
/ 29 мая 2020

Мне нужно прочитать CSV-файл, содержащий количество зараженных людей по стране и за день, и вставить строки в базу данных MYSQL, используя python. Я уже создал базу данных, и она содержит такое же количество столбцов, как и файл CSV. Когда я пытаюсь запустить приведенный ниже код, я получаю следующее сообщение об ошибке: «ValueError: не удалось обработать параметры». Не могли бы вы взглянуть и сообщить мне, если что-то не так с кодом? Большое спасибо!

import pandas as pd
import mysql.connector


mydb = mysql.connector.connect(
  host="127.0.0.1",
  user="root",
  passwd="xxxx",
  database="covid19_ca"
)

mycursor = mydb.cursor()

dataframe = pd.read_csv('total_cases_modified.csv')
print(dataframe)

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

for _, row in dataframe.iterrows():
    values = (row['date'], row['World'], row['Afghanistan'], row['Albania'], row['Algeria'], row['Andorra'], row['Angola'], row['Anguilla'], row['AntiguaAndBarbuda'], row['Argentina'], row['Armenia'], row['Aruba'], row['Australia'], row['Austria'], row['Azerbaijan'], row['Bahamas'], row['Bahrain'], row['Bangladesh'], row['Barbados'], row['Belarus'], row['Belgium'], row['Belize'], row['Benin'], row['Bermuda'], row['Bhutan'], row['Bolivia'], row['BonaireSintEustatiusAndSaba'], row['BosniaAndHerzegovina'], row['Botswana'], row['Brazil'], row['BritishVirginIslands'], row['Brunei'], row['Bulgaria'], row['BurkinaFaso'], row['Burundi'], row['Cambodia'], row['Cameroon'], row['Canada'], row['CapeVerde'], row['CaymanIslands'], row['CentralAfricanRepublic'], row['Chad'], row['Chile'], row['China'], row['Colombia'], row['Comoros'], row['Congo'], row['CostaRica'], row['CotedIvoire'], row['Croatia'], row['Cuba'], row['Curacao'], row['Cyprus'], row['CzechRepublic'], row['DemocraticRepublicCongo'], row['Denmark'], row['Djibouti'], row['Dominica'], row['DominicanRepublic'], row['Ecuador'], row['Egypt'], row['ElSalvador'], row['EquatorialGuinea'], row['Eritrea'], row['Estonia'], row['Ethiopia'], row['FaeroeIslands'], row['FalklandIslands'], row['Fiji'], row['Finland'], row['France'], row['FrenchPolynesia'], row['Gabon'], row['Gambia'], row['Georgia'], row['Germany'], row['Ghana'], row['Gibraltar'], row['Greece'], row['Greenland'], row['Grenada'], row['Guam'], row['Guatemala'], row['Guernsey'], row['Guinea'], row['GuineaBissau'], row['Guyana'], row['Haiti'], row['Honduras'], row['Hungary'], row['Iceland'], row['India'], row['Indonesia'], row['International'], row['Iran'], row['Iraq'], row['Ireland'], row['IsleofMan'], row['Israel'], row['Italy'], row['Jamaica'], row['Japan'], row['Jersey'], row['Jordan'], row['Kazakhstan'], row['Kenya'], row['Kosovo'], row['Kuwait'], row['Kyrgyzstan'], row['Laos'], row['Latvia'], row['Lebanon'], row['Lesotho'], row['Liberia'], row['Libya'], row['Liechtenstein'], row['Lithuania'], row['Luxembourg'], row['Macedonia'], row['Madagascar'], row['Malawi'], row['Malaysia'], row['Maldives'], row['Mali'], row['Malta'], row['Mauritania'], row['Mauritius'], row['Mexico'], row['Moldova'], row['Monaco'], row['Mongolia'], row['Montenegro'], row['Montserrat'], row['Morocco'], row['Mozambique'], row['Myanmar'], row['Namibia'], row['Nepal'], row['Netherlands'], row['NewCaledonia'], row['NewZealand'], row['Nicaragua'], row['Niger'], row['Nigeria'], row['NorthernMarianaIslands'], row['Norway'], row['Oman'], row['Pakistan'], row['Palestine'], row['Panama'], row['PapuaNewGuinea'], row['Paraguay'], row['Peru'], row['Philippines'], row['Poland'], row['Portugal'], row['PuertoRico'], row['Qatar'], row['Romania'], row['Russia'], row['Rwanda'], row['SaintKittsAndNevis'], row['SaintLucia'], row['SaintVincentAndtheGrenadines'], row['SanMarino'], row['SaoTomeAndPrincipe'], row['SaudiArabia'], row['Senegal'], row['Serbia'], row['Seychelles'], row['SierraLeone'], row['Singapore'], row['SintMaarten'], row['Slovakia'], row['Slovenia'], row['Somalia'], row['SouthAfrica'], row['SouthKorea'], row['SouthSudan'], row['Spain'], row['SriLanka'], row['Sudan'], row['Suriname'], row['Swaziland'], row['Sweden'], row['Switzerland'], row['Syria'], row['Taiwan'], row['Tajikistan'], row['Tanzania'], row['Thailand'], row['Timor'], row['Togo'], row['TrinidadAndTobago'], row['Tunisia'], row['Turkey'], row['TurksAndCaicosIslands'], row['Uganda'], row['Ukraine'], row['UnitedArabEmirates'], row['UnitedKingdom'], row['UnitedStates'], row['UnitedStatesVirginIslands'], row['Uruguay'], row['Uzbekistan'], row['Vatican'], row['Venezuela', row['Vietnam'], row['WesternSahara'], row['Yemen'], row['Zambia'], row['Zimbabwe'])
    mycursor.execute('INSERT INTO covid_per_day_per_country (date, World, Afghanistan, Albania, Algeria, Andorra, Angola, Anguilla, AntiguaAndBarbuda, Argentina, Armenia, Aruba, Australia, Austria, Azerbaijan, Bahamas, Bahrain, Bangladesh, Barbados, Belarus, Belgium, Belize, Benin, Bermuda, Bhutan, Bolivia, BonaireSintEustatiusAndSaba, BosniaAndHerzegovina, Botswana, Brazil, BritishVirginIslands, Brunei, Bulgaria, BurkinaFaso, Burundi, Cambodia, Cameroon, Canada, CapeVerde, CaymanIslands, CentralAfricanRepublic,Chad, Chile, China, Colombia, Comoros, Congo, CostaRica, CotedIvoire, Croatia, Cuba, Curacao, Cyprus, CzechRepublic, DemocraticRepublicCongo, Denmark, Djibouti, Dominica, DominicanRepublic, Ecuador, Egypt, ElSalvador, EquatorialGuinea, Eritrea, Estonia, Ethiopia, FaeroeIslands, FalklandIslands, Fiji, Finland, France, FrenchPolynesia,Gabon, Gambia, Georgia, Germany, Ghana, Gibraltar, Greece, Greenland, Grenada, Guam, Guatemala, Guernsey, Guinea, GuineaBissau, Guyana, Haiti, Honduras, Hungary, Iceland, India, Indonesia, International, Iran, Iraq, Ireland, IsleofMan, Israel, Italy, Jamaica, Japan, Jersey, Jordan, Kazakhstan, Kenya, Kosovo, Kuwait, Kyrgyzstan, Laos, Latvia, Lebanon, Lesotho, Liberia, Libya, Liechtenstein, Lithuania, Luxembourg, Macedonia, Madagascar, Malawi, Malaysia, Maldives, Mali, Malta, Mauritania, Mauritius, Mexico, Moldova, Monaco, Mongolia, Montenegro, Montserrat, Morocco, Mozambique, Myanmar, Namibia, Nepal, Netherlands, NewCaledonia, NewZealand, Nicaragua, Niger, Nigeria, NorthernMarianaIslands, Norway, Oman, Pakistan, Palestine, Panama, PapuaNewGuinea, Paraguay, Peru, Philippines, Poland, Portugal, PuertoRico, Qatar, Romania, Russia, Rwanda, SaintKittsAndNevis, SaintLucia, SaintVincentAndtheGrenadines, SanMarino, SaoTomeAndPrincipe, SaudiArabia, Senegal, Serbia, Seychelles, SierraLeone, Singapore, SintMaarten, Slovakia, Slovenia, Somalia, SouthAfrica, SouthKorea, SouthSudan, Spain, SriLanka, Sudan, Suriname, Swaziland, Sweden, Switzerland, Syria, Taiwan, Tajikistan, Tanzania, Thailand, Timor, Togo, TrinidadAndTobago, Tunisia, Turkey, TurksAndCaicosIslands, Uganda, Ukraine, UnitedArabEmirates, UnitedKingdom, UnitedStates, UnitedStatesVirginIslands, Uruguay, Uzbekistan, Vatican, Venezuela, Vietnam, WesternSahara, Yemen, Zambia, Zimbabwe) VALUES("%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s")', values)

mydb.commit ()


values = (row['Antigua and Barbuda'])
mycursor.execute('INSERT INTO covid_per_day_per_country (Antigua and Barbuda) VALUES ("%s")', values)

ProgrammingError: 1064 (42000): у вас есть ошибка в SQL синтаксис; проверьте руководство, соответствующее вашей версии сервера MySQL, чтобы найти правильный синтаксис для использования рядом с 'и Barbuda) VALUES ("% s")' в строке 1

1 Ответ

0 голосов
/ 29 мая 2020

Предпочтительный способ pandas - использовать функцию to_sql. Сначала установите пакет sqlalchemy. Тогда попробуйте этот код. Имена столбцов в таблице и фрейме данных должны быть одинаковыми.

from sqlalchemy import create_engine

engine = create_engine('mysql://root:xxxx@127.0.0.1/')
dataframe.to_sql('covid19_ca', engine)

Если вы хотите продолжать использовать свой код и перебирать фрейм данных (обратите внимание, что не рекомендуется ), вы можете попробовать что-то вроде этого:

for _, row in dataframe.iterrows():
    values = (row['date'], row['World'], row['Afghanistan'])
    mycursor.execute('INSERT INTO covid_per_day_per_country (date, World, Afghanistan) VALUES("%s", "%s", "%s")', values)
    mydb.commit()
...