Error inserting CSV data into Mysql with Python

Asked

Viewed 92 times

0

I am writing a Python code that inserts the data of a CSV into a Mysql table.

if os.path.isfile('\\offline.csv'):

        try:
                csv = csv.reader(open('\\offline.csv', encoding='utf-8'))
                for row in csv:
                    conn = connect()
                    cursor = conn.cursor()
                    query = "INSERT INTO maquina(processador, mb_fabricante, mb_modelo, mb_num_serie, sis_hostname, sis_versao_sistema, sis_data_instalacao, rede_ipv4, rede_macaddress, rede_srv_dns, memoria_ram, total_hd, nome_tecnico)VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);"
                    cursor.execute(query, row)                    
                    conn.commit()
                    print('sucesso csv')
                    cursor.close()
                    conn.close()
        except Exception as erro:
                    print('erro csv', erro)

The problem that occurs is the following: the header data that are the names of the database columns are inserted as records, but the following data, which would be inserted to return the error: csv not enough arguments for format string. The CSV is this:

I would like to ignore the header data and just insert the next row. I have tried to manually delete the header but the error persists.

1 answer

1


At first the code is OK. From the file print . csv I believe the error is the blank line between the header and the first line.

inserir a descrição da imagem aqui

Place a check if the line is empty

for row in csv:
    if len( row ) == 0:
        continue
  • It worked perfectly, the error was related to blank line. I lost almost two days cracking my head. Very grateful.

  • It happens a lot with everyone :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.