簡體   English   中英

LOAD DATA LOCAL INFILE上的Python2.7 MySQL連接器錯誤

[英]Python2.7 MySQL Connector Error on LOAD DATA LOCAL INFILE

我正在嘗試使用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.connect時,添加字段allow_local_infile = "True" 它會工作的

好的,這就是我的想法。

@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版本不允許使用的命令

有幾個站點表明可以通過在MySQL Connector配置中添加“local_infile = 1”來修復此問題。 這是一個: http//dev.mysql.com/doc/refman/5.1/en/loading-tables.html

這個解決方案對我不起作用。 我的local_infile在MySQL上設置為1,我不能在Python代碼中設置它,或者我得到一個e

我將用一些逐行讀取CSV文件並將行插入數據庫的東西替換LOAD LOCAL DATA INFILE。 這將使代碼更容易移植到其他數據庫。

調用execute()方法時出錯:

cursor.execute(add_csv_file,csv_info)

嘗試:

cursor.execute(query,(add_csv_file,csv_info,))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM