python - 异常处理程序不工作 : Commiting to SQL Database with SQLAlchemy in Python

标签 python mysql sqlalchemy try-catch

我正在尝试使用 Python 中的 SQLAlchemy 将条目提交到 MySQL 数据库。下面的函数旨在允许我提交一批条目,即使其中一两个条目包含数据库不接受的错误。但是,当它到达无法提交的条目时,它不会跳过该条目并转到下一个条目,而是尝试一遍又一遍地提交相同的条目,从而为该条目获取相同的错误消息一千次。为什么我的函数中的 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 中时,它并不孤单,刚刚失败的对象仍然存在。将 session.rollback() 添加到 except block 将从 session 中删除无法保存到数据库的对象,从而允许保存下一个对象。

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 - 异常处理程序不工作 : Commiting to SQL Database with SQLAlchemy in Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21197304/

相关文章:

python - 从 scipy.sparse.linalg.cg 中的回调打印当前残差

php - 在 MySQL 中存储列表的正确方法是什么?

php - foreach保存到mysqli

python - "MySQL server has gone away"长时间空闲后出现错误

python - 使用外键映射从使用 Python 和 SQLAlchemy 的其他表中获取数据

python - 如何使用基于使用列的函数的条件选择 Python Dataframe 中的行

python - 如何在 Python 中将数据附加到嵌套 JSON 文件

python - Matplotlib Latex 分数中的垂直间距

mysql - 如何连接到托管服务器上禁用的远程 MySQL?

postgresql - 在 sqlalchemy orm 中定义模式名称和约束