在Python中将数据从MySQL导出到CSV

时间:2020-08-04 07:12:04

标签: python mysql mysql-connector

import mysql.connector

sql = "SELECT r.sensorID, s.area, r.date, r.Time, r.waterLevel, r.redalert FROM sensor s INNER JOIN rainfall r ON s.sensorID = r.sensorID ORDER BY r.date, Time INTO OUTFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/rainDB.csv' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\n';"

mycursor.execute(sql)

我想在我的Python IDE中执行以上代码,以将数据导出到CSV文件。 select语句在MySQL工作台中工作正常。但是,当我在Pycharm中尝试时,仍然出现以下错误:

File "C:/Users/user/PycharmProjects/pythonProject1/BIrainSensor.py", line 106
    sql = "SELECT r.sensorID, s.area, r.date, r.Time, r.waterLevel, r.redalert FROM sensor s INNER JOIN rainfall r ON s.sensorID = r.sensorID ORDER BY r.date, Time INTO OUTFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/rainDB.csv' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\n';"
                                                                                                                                                                                                                                                                                                                         ^
SyntaxError: unexpected character after line continuation character

我认为这是由于引号内的反斜杠n(\ n)。有没有解决此问题的方法,还是我应该寻找另一种方法将数据导出到CSV文件。

1 个答案:

答案 0 :(得分:0)

您需要添加\(反斜杠)以转义"(因为您正在使用它来定义查询字符串)和\字符。

请参考Python字符串和字节文字https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals

示例:

sql = "SELECT r.sensorID, s.area, r.date, r.Time, r.waterLevel, r.redalert FROM sensor s INNER JOIN rainfall r ON s.sensorID = r.sensorID ORDER BY r.date, Time INTO OUTFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/rainDB.csv' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY '\\n'"

甚至更好的是,您可以使用带前缀字母“ r”的三引号字符串将其标记为原始字符串。这样可以避免转义字符:

sql = r"""SELECT r.sensorID, s.area, r.date, r.Time, r.waterLevel, r.redalert
FROM sensor s
INNER JOIN rainfall r ON s.sensorID = r.sensorID
ORDER BY r.date, Time
INTO OUTFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/rainDB.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\n'
"""