3

我正在尝试使用 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()

提前谢谢你的帮助!

4

4 回答 4

3

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

于 2019-03-04T15:24:18.970 回答
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()
于 2014-08-25T23:28:11.150 回答
1

好的,这就是我想出来的。

@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): The used command is not allowed with this MySQL version

有几个站点表明可以通过将“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 文件并将行插入数据库的内容。无论如何,这将使代码更易于移植到其他数据库。

于 2013-10-03T15:13:34.353 回答
0

调用 execute() 方法时出现错误:

cursor.execute(add_csv_file, csv_info)

尝试:

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

于 2013-10-02T18:01:06.397 回答