Escaping MySQL LOAD DATA INFILE command

时间:2018-01-15 18:17:41

标签: python mysql csv

I want to escape this command in Python 3.6, as I want to use it to run it through a bulk of csv files.

for filename in glob.glob(CSV_FOLDER_LOCATION + "/*.csv"):
    # Adds quotes to filename because of the problem caused by spaces in path names
    quoted_filename = '"' + filename + '"'
    os.system(MYSQL_LOCATION + r" -u root LOAD DATA INFILE " + quoted_filename + " INTO TABLE " + TABLE_NAME +
              r" CHARACTER SET ascii FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '/n' IGNORE 1 LINES")

The comma shows up as whitespace. This is the output:

C:/Program Files/MySQL/MySQL Server 5.7/bin/mysql.exe -u root LOAD DATA INFILE "C:/prog/csv/CSVFiles\CC19711977ZWEIG-ZZ.csv" INTO TABLE vcc2.tmp_cards CHARACTER SET ascii FIELDS TERMINATED BY   ENCLOSED BY '"' LINES TERMINATED BY '/n' IGNORE 1 LINES

What is the correct way to escape that string?

Edit: Added image for clarification: enter image description here

Maybe I'm really thick and missing something obvious, but how can I "raw string" it C-style?

1 个答案:

答案 0 :(得分:0)

以这种方式逃脱:

os.system(
            r"LOAD DATA LOCAL INFILE " + '"' + CSV_FOLDER_LOCATION + '/' + filename + '"' + " INTO TABLE " + TABLE_NAME +
            r' CHARACTER SET ascii FIELDS TERMINATED BY ' + '\',\'' + ' ENCLOSED BY ' + '\'"\'' +
            ' LINES TERMINATED BY ' + '\'\\n\'' + ' IGNORE 1 LINES')