MySQL / Python LOAD DATA LOCAL INFILE错误

时间:2016-03-15 22:19:47

标签: python mysql

我正在使用OSX 10.10.5和MySQL 5.7.11并尝试将txt数据加载到mysql表。我的代码工作,直到我添加load_data函数。

import pymysql as mdb
import os

def connect(user, password):
    return mdb.connect('localhost', user, password, local_infile=True)

def create_table(name):
    cursor.execute("""drop table if exists %s """ % (name))
    cursor.execute("""create table %s(try VARCHAR(4))""" %(name))

def load_data(file_name, table_name):
    load_data="""load data local infile "%s" into table %s""" % (file_name, table_name)
    cursor.execute(load_data)

con = connect('root','xxx')
cursor = con.cursor()
cursor.execute("use mydb")

table_names = ['dbtry','dbtry1','dbtry2']
file_names = os.listdir("/usr/local/mysql/bin/try")
for i in range(0,3):
    create_table(table_names[i])
    load_data(file_names[i],table_names[i])

con.close()

然后代码发出了这个错误:

ERROR 1148: The used command is not allowed with this MySQL version

它指示我:

 http://dev.mysql.com/doc/refman/5.7/en/load-data-local.html

然后我找到了" my-default.cnf" in" / usr / local / mysql / support-files"并将其复制到" / etc"。我在[mysqld]下添加了local-infile = 1。当我问MySQL时:

 SHOW VARIABLES LIKE "local%";
它给了我:

 +---------------+-------+
 | Variable_name | Value |
 +---------------+-------+
 | local_infile  | ON    |
 +---------------+-------+

最后,当我添加local_infile = True来返回connect函数时,它引发了一个新的错误:

File "/Volumes/RADYO/dbtry.py", line 26, in <module>
  load_data(file_names[i],table_names[i])
File "/Volumes/RADYO/dbtry.py", line 15, in load_data
  cursor.execute(load_data)
File "/Users/elf/Desktop/elif/mysql-env/lib/python2.7/site-packages/pymysql/cursors.py", line 158, in execute
  result = self._query(query)
File "/Users/elf/Desktop/elif/mysql-env/lib/python2.7/site-packages/pymysql/cursors.py", line 308, in _query
  conn.query(q)
File "/Users/elf/Desktop/elif/mysql-env/lib/python2.7/site-packages/pymysql/connections.py", line 820, in query
  self._affected_rows = self._read_query_result(unbuffered=unbuffered)
File "/Users/elf/Desktop/elif/mysql-env/lib/python2.7/site-packages/pymysql/connections.py", line 1002, in _read_query_result
  result.read()
File "/Users/elf/Desktop/elif/mysql-env/lib/python2.7/site-packages/pymysql/connections.py", line 1290, in read
  self._read_load_local_packet(first_packet)
File "/Users/elf/Desktop/elif/mysql-env/lib/python2.7/site-packages/pymysql/connections.py", line 1326, in _read_load_local_packet
  sender.send_data()
File "/Users/elf/Desktop/elif/mysql-env/lib/python2.7/site-packages/pymysql/connections.py", line 1457, in send_data
  raise err.OperationalError(1017, "Can't find file '{0}'".format(self.filename))
pymysql.err.OperationalError: (1017, "Can't find file 'try1.txt'")

但是有文件&#39; try1.txt&#39;在目录中。我该如何解决这个问题呢?

1 个答案:

答案 0 :(得分:4)

pymysql客户端可能存在问题。您似乎应该能够执行以下操作:

def connect(user, password):
    return mdb.connect('localhost', user, password,local_infile=True)
相关问题