【问题标题】:load Local infile csv to mysql db fails将本地 infile csv 加载到 mysql db 失败
【发布时间】:2018-03-30 04:19:36
【问题描述】:

我试图将我的 csv 文件导入数据库。但它失败了。

    # -*- 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(最近一次调用最后一次):文件“test.py”,第 30 行,在 database.insert_csv_test() 文件“test.py”,第 20 行,在 insert_csv_test self.cursor.execute(查询)文件“/Library/Python/2.7/site-packages/MySQL_python-1.2.4b4-py2.7-macosx-10.12-intel.egg/MySQLdb/cursors.py”, 第 202 行,执行中 self.errorhandler(self, exc, value) 文件“/Library/Python/2.7/site-packages/MySQL_python-1.2.4b4-py2.7-macosx-10.12-intel.egg/MySQLdb/connections.py”, 第 36 行,在默认错误处理程序中 引发错误类,错误值 _mysql_exceptions.ProgrammingError: (1064, "您的 SQL 语法有错误;请查看与您的 MySQL 服务器对应的手册 在附近使用正确语法的版本 '\xe2\x80\x98/Users/ankr/Desktop/output\xe2\x80\x99 INTO TABLE 详细信息 第 1 行由 \xe2\x80\x98,\xe2\x80\x99 LI' 终止的字段")

任何帮助将不胜感激。

【问题讨论】:

  • 看起来你的 csv 路径周围有花引号。

标签: python mysql django database csv


【解决方案1】:

这可能是一个有点幼稚的答案,但我认为问题在于 字符。它被解释为 UTF-8 字符。尝试将其替换为常规单引号 - '

【讨论】:

    【解决方案2】:

    看起来你至少在通话中遇到了问题。您正在连接数据库两次:

    database = Database()
    database.__init__()
    

    你应该运行:

    database = Database()
    

    您应该在 SQL 查询中使用 \'(而不是 '),因为您希望避免它们被直接解释为另一条评论中已经提到的。

    【讨论】:

    • 谢谢。我得到了它。这是因为引号(')而不是(')
    猜你喜欢
    • 1970-01-01
    • 2011-05-25
    • 2013-12-12
    • 2012-10-20
    • 2012-10-26
    • 2015-04-07
    • 2011-12-07
    • 1970-01-01
    • 2015-03-27
    相关资源
    最近更新 更多