ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

LOAD DATA LOCAL INFILE上的Python2.7 MySQL连接器错误

2019-08-31 12:55:42  阅读:267  来源: 互联网

标签:mysql-connector python mysql python-2-7


我正在尝试使用Python和MySQL Connector将人口普查数据动态加载到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()

提前谢谢你的帮助!

解决方法:

通过在连接中添加适当的客户端标志,可以轻松解决此问题,如下所示:

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

标签:mysql-connector,python,mysql,python-2-7
来源: https://codeday.me/bug/20190831/1775982.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有