Python / MySQL - LOAD DATA LOCAL INFILE

时间:2014-08-29 17:10:56

标签: python mysql csv

我正在使用Python的mysql连接器,我尝试通过Python(Windows)运行以下SQL语句 - 它是一个.csv文件:

sql1 = ('SET GLOBAL local_infile = "ON";')
cursor.execute(sql1)

sql2 = ('LOAD DATA LOCAL INFILE "' + path[1:-1] + '" INTO TABLE mytable COLUMNS  TERMINATED BY "," LINES TERMINATED BY "\\r\\n" (COL0, COL1, COL2, COL3, COL4, COL5, COL6) SET COL7 = "'some_data'";')
cursor.execute(sql2)

但是当我尝试执行时,我收到以下异常:

  

1148(42000):此MySQL版本不允许使用命令

如果我尝试在mysql控制台上执行LOAD DATA LOCAL INFILE,一切运行正常。

3 个答案:

答案 0 :(得分:2)

默认情况下,使用Connector / Python禁用Load Data Infile 在创建连接时设置LOCAL_FILES客户端标志,如下所示:

from mysql.connector.constants import ClientFlag
conn = mysql.connector.connect(...., client_flags=[ClientFlag.LOCAL_FILES])

答案 1 :(得分:0)

LOAD DATA存在很多安全问题,因此服务器非常挑剔。您是否登录到localhost,而不是服务器的公共IP?通常一个IP将被授予LOAD DATA,但另一个IP将被授予。

请参阅the fine manual

答案 2 :(得分:0)

您可以遍历文件的每一行,将每个行插入一行。这很简单,因为您已经提到每个列都由,描述,每行都用换行符描述。

例如,假设您的表mytable有8个字符串列,(COL0到COL7):

input_file = open(path[1:-1], 'r')

#Loop through the lines of the input file, inserting each as a row in mytable
for line_of_input_file in input_file:
    values_from_file = line_of_input_file.split(',', 1) #get the columns from the line read from the file

    if(len(values_from_file) == 7): #ensure that 7 columns accounted for on this line of the file
        sql_insert_row = "INSERT INTO mytable VALUES (" + values_from_file[0] + "," + values_from_file[1] + "," + values_from_file[2] + "," + values_from_file[3] + "," + values_from_file[4] + "," + values_from_file[5] + "," + values_from_file[6] + "," + some_data + ");"
        cursor.execute(sql_insert_row)
input_file.close()