我正在尝试使用MySQL中的SQLAlchemy将条目提交到Python数据库。下面的函数旨在使我可以提交一批条目,即使其中的一两个条目包含数据库无法接受的错误。但是,当到达无法提交的条目时,它不会跳过并转到下一个条目,它会一遍又一遍地提交同一条目,为该条目获得相同的错误消息一千次。为什么我的函数中的trycatch不起作用?

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")

            if verbose:
                print(e)

        finally:
            counter += 1
            if verbose:
                print(counter, counter/float(len(database)))

    if verbose:
        print("Entries saved!")
    session.close()

最佳答案

当提交失败时,它不会像成功提交一样从内存中删除对象。因此,当下一个对象添加到会话中时,它并不孤单,刚刚失败的对象仍然存在。将session.rollback()添加到except块将从会话中删除无法保存到数据库的对象,从而允许保存下一个对象。

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()

关于python - 异常处理程序不起作用:使用Python中的SQLAlchemy提交到SQL数据库,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21197304/

10-14 12:53
查看更多