异常处理程序不起作用:使用Python中的SQLAlchemy提交SQL数据库

时间:2014-01-17 22:40:11

标签: python mysql sqlalchemy try-catch

我正在尝试使用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()

1 个答案:

答案 0 :(得分:1)

当提交失败时,它不会像成功提交那样从内存中删除对象。因此,当下一个对象被添加到会话时并不是唯一的,刚刚失败的对象仍然存在。将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()