我有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")
答案 0 :(得分:0)
看起来你的一个值中有一个撇号。你需要逃避撇号以避免这个错误。
例如,您有这样的值:
That's right!
所以你的插图看起来像这样:
insert into question1 values('value1','That's right!','value2');
你应该逃避撇号来制作这样的插入物:
insert into question1 values('value1','That''s right!','value2');
答案 1 :(得分:0)
在你的一条线上看起来有一个撇号搞砸了MySQL。从错误消息 -
's Solids','Men','NULL','Solid'
您的问题及其解决方案在此处得到了很好的解释 - Python MySQL escape special characters