Python - KeyError

0

Someone can help me!

I am reading from a csv file and then I do an INSERT on the MySQL database, but I get the following error

KeyError: 'id'

I have checked the CSV file several times, the file has all the columns and exactly the same name.

importcsvimportpymysql#importaoarquivodeacessoaobancofromconfigimportconfig#fazaconexãocomobancodedadoscnx=pymysql.connect(**config,charset='utf8')cursor=cnx.cursor()#leroarquivocsvinput_file=csv.DictReader(open("teste.csv", encoding='utf-8'))

# importa o arquivo csv no banco de dados
for row in input_file:
    cursor.execute("INSERT INTO teste.tabela (id,nome) \
                    VALUES (%s,%s)",(row['id'],row['nome']))
    print("Importando Linhas")
    cnx.commit()
    
asked by anonymous 01.10.2018 / 23:53

1 answer

1

Put a "print" inside for and you will immediately understand what is happening.

Only with the data you put you can not say with certainty, but if you saved the CSV of a Microsoft Excel in Portuguese, the tab will be ; , for example, instead of , - Python's csv module does not use any kind of inference to guess what the separator is.

(You can also check this by opening your CSV file in the programming editor instead of always opening it in the spreadsheet program (ie Excel, LibreOffice, GoogleSheets) - if so, as it seems, the tab is not a comma , just enter this into DictReader creation:

input_file = csv.DictReader(open("teste.csv", encoding='utf-8'), delimiter=';')
    
02.10.2018 / 04:47