简体   繁体   English

如何在将 csv 加载到数据库时在 try except 块中多次捕获单个异常

[英]How to capture single exception multiple times in try except block while loading a csv to database

I am trying to load a csv file to Mysql.我正在尝试将 csv 文件加载到 Mysql。 The file has a million records so I am doing batch insertions of 1000. I am using python libraries sqlalchemy and pymysql.该文件有一百万条记录,所以我正在批量插入 1000 条。我正在使用 python 库 sqlalchemy 和 pymysql。 After first batch insertion I am getting error第一批插入后,我收到错误

pymysql.err.InternalError) (1366, "Incorrect string value: '\xC2\x83\xC2\xB7\xC3\xA5...' pymysql.err.InternalError) (1366, "不正确的字符串值:'\xC2\x83\xC2\xB7\xC3\xA5...'

for column 'FHCNM' at row 50. I wanted to skip that particular batch and insert remaining batches.对于第 50 行的“FHCNM”列。我想跳过该特定批次并插入剩余批次。 I doing that with try..except..finally blocks in python.我用 python 中的 try..except..finally 块来做到这一点。 Here I am getting the same error (pymysql.err.InternalError) at different batches.在这里,我在不同批次收到相同的错误(pymysql.err.InternalError)。 How do I handle single exception multiple times?如何多次处理单个异常? Right now, I am trying like现在,我正在尝试

def functnname():
   try:
         #my code to insert data to mysql
   except:
         #to handle my error first time
         pass
   finally:
         #continue with next batch insertions
   return
try:
   functnname()
except:
   #to handle my error second time
finally:
    functnname()

I am trying out like this.我正在尝试这样。 I don't know if it works.我不知道它是否有效。 Any more efficient way would be appreciated.任何更有效的方式将不胜感激。 And also how to handle the above error in first place and how insert the failed batches afterwards.以及如何首先处理上述错误以及之后如何插入失败的批次。 Python 3.x. Python 3.x。

It would be hard to do in python code without inserting each element individually, but this will hurt your performance a lot.如果不单独插入每个元素,在 python 代码中很难做到这一点,但这会极大地损害您的性能。 Use mysql features to ignore / handle errors during batch insertion.使用 mysql 功能在批量插入期间忽略/处理错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM