2017-10-18 52 views
0

我试图将我的csv文件导入数据库。但它失败了。加载本地infile csv到MySQL数据库失败

# -*- coding: utf-8 -*- 
import MySQLdb 

class Database: 

    def __init__(self): 

     self.host = 'localhost' 
     self.user = 'root' 
     self.port = 3306 
     self.password = 'root' 
     self.db = 'test' 
     self.connection = MySQLdb.connect(self.host, self.user, self.password, self.db, self.port, local_infile = 1) 
     self.cursor = self.connection.cursor() 


    def insert_csv_test(self): 

     query = "LOAD DATA LOCAL INFILE ‘/Users/ankr/Desktop/output’ INTO TABLE details FIELDS TERMINATED BY ‘,’ LINES TERMINATED BY ‘\n’" 
     self.cursor.execute(query) 
     self.connection.commit() 
     self.connection.close() 
     print("Done") 

    def close_connection(self): 
     self.connection.close() 

database = Database() 
database.__init__() 
database.insert_csv_test() 
database.close_connection() 

它失败。看到下面。

Traceback (most recent call last): File "test.py", line 30, in database.insert_csv_test() File "test.py", line 20, in insert_csv_test self.cursor.execute(query) File "/Library/Python/2.7/site-packages/MySQL_python-1.2.4b4-py2.7-macosx-10.12-intel.egg/MySQLdb/cursors.py", line 202, in execute self.errorhandler(self, exc, value) File "/Library/Python/2.7/site-packages/MySQL_python-1.2.4b4-py2.7-macosx-10.12-intel.egg/MySQLdb/connections.py", line 36, in defaulterrorhandler raise errorclass, errorvalue _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\xe2\x80\x98/Users/ankr/Desktop/output\xe2\x80\x99 INTO TABLE details FIELDS TERMINATED BY \xe2\x80\x98,\xe2\x80\x99 LI' at line 1")

任何帮助,将不胜感激。

+0

看起来你的csv路径上有引号。 –

回答

1

这可能是一个天真的答案,但我认为问题在于字符。它被解释为一个UTF-8字符。尝试用普通单引号替换它 - '

1

看起来你至少在通话中有问题。要连接到数据库两次:

database = Database() 
database.__init__() 

你应该只运行:

database = Database() 

您应该使用\“(SQL查询没有)里面”,因为你想避免他们被直接解释如另一评论中已经提到的那样。

+0

谢谢。我知道了。这是因为引号(')不是(') – Anjanaa