Anjanaa
Anjanaa

Reputation: 488

load Local infile csv to mysql db fails

I trying to import my csv file into database. but it fails.

    # -*- 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()

It fails. Seeing this below.

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")

Any Help would be appreciated.

Upvotes: 0

Views: 195

Answers (2)

Eamonn Kenny
Eamonn Kenny

Reputation: 2072

Looks like you at least have a problem in the call. You are connecting to the database twice:

database = Database()
database.__init__()

You should just run:

database = Database()

You should be using \' inside the SQL query (not ') since you want to avoid them being directly interpreted as mentioned already in another comment.

Upvotes: 1

Artsiom Vahin
Artsiom Vahin

Reputation: 59

This may be a little naive answer, but I think the problem lies in character. It's getting interpreted as a UTF-8 character. Try replacing it with a regular single quote - ' .

Upvotes: 1

Related Questions