使用python将csv文件加载到mysql时出现语法错误

时间:2017-01-31 22:09:42

标签: python mysql csv

我通过os和glob模块得到了csv文件的路径:

os.chdir('C:\myproject')
filename = glob.glob('*.csv')
new1 = str(filename[0]).strip("''") 
path1 =  'C:\myproject\\' + new1 

然后使用MySQLdb将其加载到数据库:

cursor.execute("LOAD DATA LOCAL INFILE {0} INTO TABLE intens FIELDS \
TERMINATED BY ',' IGNORE 1 LINES (ID, @timevar, intensity) set in_time = \
STR_TO_DATE(@timevar, '%m/%d/%Y %r'), record_ID =  \            
LAST_INSERT_ID()".format(path1,))

当我在INFILE命令之后直接粘贴路径时,此代码在MySQL中有效。但是,我收到以下错误消息:

File "C:\Anaconda\lib\site-packages\MySQLdb\cursors.py", line 226, in execute self.errorhandler(self, exc, value)
File "C:\Anaconda\lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler
raise errorvalue
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'C:\\myproject\\aaa.csv INTO TABLE intens FIELDS TER' at line 1")

提前谢谢。

1 个答案:

答案 0 :(得分:1)

你在文件路径周围缺少撇号

[增订]

cursor.execute("LOAD DATA LOCAL INFILE `{0}` INTO TABLE intens FIELDS TERMINATED BY `,` IGNORE 1 LINES (ID, @timevar, intensity) set in_time = STR_TO_DATE(@timevar, `%m/%d/%Y %r`), record_ID = LAST_INSERT_ID()".format(glob.glob(r'c:\myproject\*.csv')[0]))