2017-05-03 22 views
1

我是python.py的新手,我想用mysql.connector和python连接mysql。我想打开一个csv,然后把它上传到mysql数据库。我用的是python版本:3.6.0用python连接到mysql并上传csv

我已经试过这一个:

import csv 
import mysql.connector 

cnx = mysql.connector.connect(user='', password='', 
           host='127.0.0.1', 
           database='') 
csv_data = csv.reader(file('12_13.csv')) 
for row in csv_data: 

    cursor.execute('INSERT INTO testcsv(names, \ 
      classes, mark)' \ 
      'VALUES("%s", "%s", "%s")', 
      row) 
#close the connection to the database. 
mydb.commit() 
cursor.close() 
print("Done") 

我收到此错误:

Traceback (most recent call last): File ".\uploadtomysql.py", line 7, in csv_data = csv.reader(file('12_13.csv')) NameError: name 'file' is not defined

谢谢!

回答

0

试试这个:

csv.reader(filename, delimiter=',') 
0

你所得到的错误是,'file' is not defined。这是因为您正在传递一个名为file的变量,该变量未在程序中的任何位置定义(或导入)。您可能打算将file设置为您想要读取的.csv文件。所以,第一步是打开一个文件:

file = open('12_13.csv', 'rb') # open the file in read binary mode 
... 
file.close() 

或更好,但打开上下文管理器的文件,这意味着一旦执行退出该块它会自动关闭:

with open('12_13.csv', 'rb') as f: 
    csv_data = csv.reader(f) # No NameError 
    ... 
f # raises NameError and file is closed 

我没有”运行代码,但这应该可以解决您提到的错误,或者至少可以让您朝正确的方向发展。

您还将遇到cursor未定义的问题。您需要创建一个新的光标cnx.cursor()

最后,mydb也未定义,因此会引发错误。我不认为你需要在这方面做出承诺,但我不能肯定地说。对于这种控制,我建议使用一个ORM,如SQLAlchemy