【问题标题】:Python2.7 MySQL Connector Error on LOAD DATA LOCAL INFILELOAD DATA LOCAL INFILE 上的 Python2.7 MySQL 连接器错误
【发布时间】:2013-10-09 05:26:30
【问题描述】:

我正在尝试使用 Python 和 MySQL 连接器将人口普查数据动态加载到 mysql 数据库中(来自 .csv 文件)。

我不知道为什么会出现错误:

Traceback (most recent call last):
  File "miner.py", line 125, in <module>
    cursor.execute(add_csv_file, csv_info)
  File "/Library/Python/2.7/site-packages/mysql/connector/cursor.py", line 393, in execute
    self._handle_result(self._connection.cmd_query(stmt))
  File "/Library/Python/2.7/site-packages/mysql/connector/connection.py", line 586, in cmd_query
statement))
  File "/Library/Python/2.7/site-packages/mysql/connector/connection.py", line 508, in _handle_result
    raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1064 (42000): 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 '/Users/afink/Documents/Research/Current Papers & Books/Youth Assessm' at line 1

执行前输出的字符串在同一用户下的 MySQL 命令行界面中可以正常工作。

似乎这应该是一个简单的问题,但我被卡住了!

def db_connect():
    config = {
        'user': 'username',
        'password': 'pass',
        'host': 'localhost',
        'database': 'uscensus',
        'raise_on_warnings': True,
    }

    from mysql.connector import errorcode
    try:
      cnx = mysql.connector.connect(**config)
      return cnx
    except mysql.connector.Error as err:
      if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        print("Something is wrong with your user name or password")
      elif err.errno == errorcode.ER_BAD_DB_ERROR:
        print("Database does not exist")
      else:
        print(err)
    else:
      cnx.close()


cursor = cnx.cursor()

os.chdir("./")
for files in glob.glob("*.csv"):

    add_csv_file = ('''load data local infile '%(cwd)s/%(file_name)s' into table %(table_name)s 
                    columns terminated by ',' 
                    optionally enclosed by '\"'
                    escaped by '\"'
                    lines terminated by '\\n';''')

    # Insert CSV file information
    csv_info = {
        'cwd': os.getcwd(),
        'file_name': files,
        'table_name': 'SF1_' + files[2:-8],
    }


    print add_csv_file % csv_info # Temporary Debug

    cursor.execute(add_csv_file, csv_info)

# Make sure data is committed to the database
cnx.commit()
cursor.close()
cnx.close()

提前感谢您的帮助!

【问题讨论】:

    标签: python mysql python-2.7 mysql-connector


    【解决方案1】:

    在执行 mysql.connector.connect 时添加字段 allow_local_infile = "True"。 它会工作的

    【讨论】:

      【解决方案2】:

      这很容易通过在您的连接中添加适当的客户端标志来解决,如下所示:

      import mysql.connector
      from mysql.connector.constants import ClientFlag
      
      cnx = mysql.connector.connect(user='[username]', password='[pass]', host='[host]', client_flags=[ClientFlag.LOCAL_FILES])
      cursor = cnx.cursor()
      

      这将允许 MySQL 访问您机器上的本地文件,然后以下 LOAD 将起作用:

      LoadSQL = """LOAD DATA LOCAL INFILE '%s'
          INTO TABLE %s
          FIELDS TERMINATED BY '\t'
          LINES TERMINATED BY '\n'
          IGNORE 1 LINES
          (field1, field2, field3, field4)""" % (csvfile, tabl_name)
      cursor.execute(LoadSQL)
      cnx.commit()
      cursor.close()
      cnx.close()
      

      【讨论】:

        【解决方案3】:

        好的,这就是我想出的。

        @Dd_tch - 你的回答帮助我意识到这段代码会更好:

        query = add_csv_file % csv_info
        cursor.execute(query)
        

        虽然连接器的 MySQL 站点似乎表明您可以做我正在做的事情 (http://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-transaction.html),但那不起作用。

        当我修复它时,我收到了一个新错误: mysql.connector.errors.ProgrammingError: 1148 (42000): 此 MySQL 版本不允许使用的命令

        有几个站点表明可以通过将“local_infile=1”添加到 MySQL 连接器配置来解决此问题。这是一个:http://dev.mysql.com/doc/refman/5.1/en/loading-tables.html

        这个解决方案对我不起作用。我的 local_infile 在 MySQL 上设置为 1,我无法在 Python 代码中设置它,否则我得到一个 e

        我将改为将 LOAD LOCAL DATA INFILE 替换为可以逐行读取 CSV 文件并将行插入数据库的内容。无论如何,这将使代码更容易移植到其他数据库。

        【讨论】:

          【解决方案4】:

          调用execute()方法时出错:

          cursor.execute(add_csv_file, csv_info)

          尝试:

          cursor.execute(查询, (add_csv_file, csv_info,))

          【讨论】:

          猜你喜欢
          • 2012-10-05
          • 1970-01-01
          • 1970-01-01
          • 2012-06-01
          • 1970-01-01
          • 2020-07-25
          • 2013-01-24
          • 1970-01-01
          相关资源
          最近更新 更多