2017-10-18 85 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