有什么可以使用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()发布于 2014-01-24 14:29:59
我觉得你看的方向不对。据我所知,当单个条目出现错误时,您无法避免不对整个批处理进行回滚而避免提交批处理。
在添加到会话之前,您应该尝试捕捉代码中的错误,即
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()最后,如果批量插入花费的时间太长,您可能希望使用insert()而不是session API。
https://stackoverflow.com/questions/21271345
复制相似问题