我正在尝试学习用Python编程.我想把csv文件放到数据库中.使用它是个好主意
我可以使用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)