1

我有 304MB 的文本文件,其中每行包含逗号(,)分隔值,我正在逐行读取文件并使用 for 循环插入值,但在插入 21 行后我不断收到此错误。这是代码

import MySQLdb

myfile = open('/home/vaibhav/Desktop/question1.csv', 'r')

db = MySQLdb.connect(host="localhost", 
                 user="root", 
                  passwd="admin", 
                  db="question1agg") 

for line in myfile:

     my_line_list = line.split(',')
     string = ''
     for value in my_line_list:
            string = string + "'" + value + "',"
            query_string = string[:-1]
      final_query = "insert into question1 values"+"("+query_string+");"
      cur = db.cursor()
      cur.execute(final_query)
      db.commit()
db.close()

这是我得到的错误

 Traceback (most recent call last):
 File "da.py", line 19, in <module>
   cur.execute(final_query)
   File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 174, in execute
   self.errorhandler(self, exc, value)
   File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in        defaulterrorhandler
   raise errorclass, errorvalue
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check    the manual that corresponds to your MySQL server version for the right syntax to use near 's Solids','Men','NULL','Solid','/Products/Legwear','/Products/Legwear/AmericanEs' at line 1")
4

2 回答 2

0

看起来您的某个值中有一个撇号。您需要转义撇号以避免该错误。

例如,您有这样的值:

That's right!

所以你的插入看起来像这样:

insert into question1 values('value1','That's right!','value2');

您应该转义撇号以进行如下插入:

insert into question1 values('value1','That''s right!','value2');
于 2013-09-24T13:46:58.153 回答
0

看起来在你的一条线上有一个撇号把 MySQL 搞砸了。从错误消息 -

's Solids','Men','NULL','Solid'

您的问题及其解决方案在这里得到了很好的解释 - Python MySQL escape special characters

于 2013-09-24T13:47:19.083 回答