gpt4 book ai didi

python - 使用for循环python在mysql表中插入值

转载 作者:行者123 更新时间:2023-11-30 23:13:18 24 4
gpt4 key购买 nike

我有一个 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")

最佳答案

看起来在您的一行中有一个撇号正在扰乱 MySQL。从错误消息 -

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

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

关于python - 使用for循环python在mysql表中插入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18983228/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com