您是否尝试过print
在将要运行的 SQL 字符串传递给之前将其输入self.cursor.execute
?
如果你这样做,你会得到这个输出:
LOAD DATA LOW_PRIORITY LOCAL INFILE 'deficiency.csv' REPLACE INTO TABLE retailstore.deficiency CHARACTER SET utf8 FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY ' ESCAPED BY ' LINES TERMINATED BY '
' IGNORE 1 LINES
仔细看看这个,你会注意到一些关于它的事情:
OPTIONALLY ENCLOSED BY
并且ESCAPED BY
后面只有 a '
,而不是'"'
您可能期望的那样,
- 之后有一个换行符
TERMINATED BY '
。
OPTIONALLY ENCLOSED BY
要修复它,您需要转义and之后的双引号字符ESCAPED BY
,以及 中的反斜杠\r\n
:
self.cursor.execute("LOAD DATA LOW_PRIORITY LOCAL INFILE 'deficiency.csv' \
REPLACE INTO TABLE retailstore.deficiency CHARACTER SET utf8 \
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' ESCAPED BY '\"' LINES TERMINATED BY '\\r\\n' \
IGNORE 1 LINES")
或者,如果您使用三引号原始字符串,则不需要转义双引号字符和 中的反斜杠\r\n
,也不需要每行末尾的尾随反斜杠:
self.cursor.execute(r"""LOAD DATA LOW_PRIORITY LOCAL INFILE 'deficiency.csv'
REPLACE INTO TABLE retailstore.deficiency CHARACTER SET utf8
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' ESCAPED BY '"' LINES TERMINATED BY '\r\n'
IGNORE 1 LINES""")
您可能想知道为什么您的原始代码会生成它所做的输出。原因是您实际上有三个彼此相邻的字符串文字。其中之一是
"LOAD DATA LOW_PRIORITY LOCAL INFILE 'deficiency.csv' \
REPLACE INTO TABLE retailstore.deficiency CHARACTER SET utf8 \
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"
下一个是
' ESCAPED BY '
(Python 中的字符串文字可以用'
or包围"
),最后一个是
"' LINES TERMINATED BY '\r\n' \
IGNORE 1 LINES"
如果将两个字符串文字并排放置,Python 会将它们连接在一起:
>>> print("12"'34'"56")
123456