Mic*_*ael 2 python mysql sql sqlalchemy
我可以使用SQLAlchemy将条目提交到具有容错容错的SQL数据库吗?将大批条目一起提交效率要高得多,但如果其中一个条目中存在错误,例如整数列中的文本,则整个批处理无法保存到数据库中.我下面的解决方法单独提交条目,但是这种方法可能会创建太多与mysql服务器的连接,特别是在并行运行时.是否有更有效的方式将条目作为批处理提交,但有错误的余地?
def commitentry(database, enginetext, verbose = False):
"""
Takes a database object and text string that defines the SQL
engine and adds all entries in the database list to the SQL
database.
"""
engine = create_engine(enginetext)
Session = sessionmaker()
Session.configure(bind=engine)
session = Session()
counter = 0
for entry in database:
try:
session.add(entry)
session.commit()
except Exception, e:
print("Commit Error")
session.rollback()
if verbose:
print(e)
finally:
counter += 1
if verbose:
print(counter, counter/float(len(database)))
if verbose:
print("Entries saved!")
session.close()
Run Code Online (Sandbox Code Playgroud)
我认为你没有看到正确的方向.据我所知,当单个条目中出现错误时,您无法避免在整个批处理中没有回滚的情况下提交批处理.
在添加到会话之前,您应该尝试捕获代码中的错误,即
batch_size = 500
for i, entry in enumerate(database_list):
try:
validate(entry)
#your custom function that validates the entry,
#throws ValidationError on error and/or tries to 'fix' the entry
session.add(entry)
except ValidationError:
pass
if (i + 1) % batch_size == 0:
#commit every `batch_size` entries
session.commit()
Run Code Online (Sandbox Code Playgroud)
最后,如果您的批量插入时间过长,您可能希望使用API insert()代替sessionAPI.
| 归档时间: |
|
| 查看次数: |
643 次 |
| 最近记录: |