gpt4 book ai didi

Python CSV 上传错误处理程序

转载 作者:行者123 更新时间:2023-11-29 07:36:58 26 4
gpt4 key购买 nike

我有一个简单的脚本,可以从一个数据库 (Teradata) 下载数据,对其执行一些操作,然后将其上传到另一个 (MySQL) 数据库。这几个月来一直运行良好,但昨天在我的日志中我注意到脚本失败,并返回了这个错误:

An error has occurred: 
(<class '_mysql_exceptions.ProgrammingError'>, 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 \'A435", NULL, "2018-01-18", 95,\' at line 1'), <traceback object
at 0x00000000019A1A48>)

似乎罪魁祸首可能是用户可编辑的字段之一,尽管这些字段中的每一个在写入数据库之前都由 PHP 中的 mysqli_real_escape_string 处理 - 所以不确定。

虽然从编程的角度来看,准确理解这里发生的事情会很好,我更关心的是编辑 python 脚本以包含一个错误处理程序,该处理程序只会跳过任何导致错误的行而不是退出整个脚本。

这是脚本:

# Upload this to MySQL
db = MySQLdb.connect(host='asdf',user='asdf',passwd='asdf',db='asdf')
cursor = db.cursor()

csv_data = csv.reader(file(csvfilename))
for row in csv_data:
cursor.execute('INSERT INTO `test` (field_1,field_2,field_3,field_4,field_5)'\
'VALUES(%s,%s,%s,%s,%s)',row);

db.commit()
# Close the connection to the database.
cursor.close()

最佳答案

当使用MySQLdb包时,三重引号用于引用查询字符串:

来自链接的文档:http://mysql-python.sourceforge.net/MySQLdb.html

db.query("""SELECT spam, eggs, sausage FROM breakfast WHERE price < 5""")

在您的情况下,您在解析的行中同时具有单引号和双引号可能是巧合,然后脚本使插入执行崩溃。

关于Python CSV 上传错误处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48349471/

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