简体   繁体   中英

Import csv to mysql database

Here is my code to import my csv to mysql database:

import csv
import mysql.connector

cnx = mysql.connector.connect(user='root', password='',
                              host='localhost',
                              database='jeremy_db')
file = open('C:\\Users\\trendMICRO\\Desktop\\OJT\\test.csv', 'rb')  # open the file in read binary mode
csv_data = csv.reader(file)
for row in csv_data:

    cursor.execute('INSERT INTO jeremy_table_test(sha1, vsdt,trendx,notes )' 'VALUES("%s", "%s", "%s","%s")',row)
#close the connection to the database.
mydb.commit()
cursor.close()
print("Done")

It is giving me error:

   Traceback (most recent call last):
  File "C:\Users\trendMICRO\Desktop\OJT\import.py", line 11, in <module>
    cursor.execute('INSERT INTO jeremy_table_test(sha1, vsdt,trendx,notes )' 'VALUES("%s", "%s", "%s","%s")',row)
NameError: name 'cursor' is not defined

I followed the instruction here: Connect to mysql with python and upload csv

You forgot to create the cursor itself. Also you mixed up variable names. commit is only for a MySQLConnection.

import csv
import mysql.connector

mydb = mysql.connector.connect(user='root', password='',
                          host='localhost',
                          database='jeremy_db')
file = open('C:\\Users\\trendMICRO\\Desktop\\OJT\\test.csv', 'rb')  # open the file in read binary mode
csv_data = csv.reader(file)

cursor = mydb.cursor()

for row in csv_data:
    cursor.execute('INSERT INTO jeremy_table_test(sha1, vsdt,trendx,notes )' 'VALUES("%s", "%s", "%s","%s")',row)

# close the connection to the database.
mydb.commit()
cursor.close()
print("Done")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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