2014-08-29 239 views
2

我使用Python的MySQL的連接器,我試圖運行通過Python(Windows)中的下列SQL語句 - 這是一個.csv文件:的Python/MySQL的 - LOAD DATA LOCAL INFILE

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

如果我嘗試執行LOAD DATA LOCAL INFILE在MySQL控制檯上,一切運行良好。

+0

哪個命令是問題? sql1或sql2? – mgilson 2014-08-29 17:27:24

+0

sql2是問題 – heliosk 2014-08-29 17:38:59

回答

2

LOAD DATA INFILE默認情況下,用連接器/ Python的 禁用,同時創造設置LOCAL_FILES客戶標誌像連接這個:

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

它確實有效。我嘗試過一次,但我忘了添加導入。 – heliosk 2014-09-01 11:01:45

0

LOAD DATA有很多安全問題,所以服務器真的很挑剔。您是否登錄到本地主機,而不是服務器的公共IP?通常一個IP將被授予LOAD DATA,但另一個不會。

the fine manual

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

執行'INSERT'需要很長時間。我必須插入數千個寄存器。這就是我選擇LOAD DATA的原因。 – heliosk 2014-09-01 11:03:54