SqlAlchemy + MySql 1205,'超过锁定等待超时;尝试重启交易'

时间:2015-07-09 09:49:45

标签: python mysql sqlalchemy flask-sqlalchemy

我正在尝试从两个表User和UserRoleMapping中删除一行。

  

UserRoleMapping使用User.id =>引用User表。 UserRoleMapping.user_id。

我需要使用特定于用户的id从两个表中删除一行。

我的代码

session_delete_mapping = Session()
session_delete_user= Session()
if request.method == "POST":
    user_id = request.form['user_list']
    try :
        num_rows_deleted_map = session_delete_mapping.query(UserRoleMapping).filter(UserRoleMapping.user_id == user_id).delete()
        num_rows_deleted_user = session_delete_user.query(UserRoleMapping).filter(User.id == user_id).delete()
        session_delete_mapping.commit()
        session_delete_user.commit()
        User.query.filter(User.id == user_id).delete()
        flash("Successfully deleted !!")
    except Exception as e:
        flash("Oops something went wrong : "+ str(e))
        session_delete_mapping.rollback()
        session_delete_user.rollback()
return render_template('index.html')

但我的代码抛出异常

  

(InternalError)(1205,'超过锁定等待超时;尝试重新启动事务')' DELETE FROM user_role_mapping WHERE user_role_mapping.user_id =%s' (' 3',)

1 个答案:

答案 0 :(得分:-1)

当服务器无法获取锁来处理带有表或数据库的操作时,会发生这种情况,尝试按照异常中的建议重新启动事务:

session_delete_mapping = Session()
session_delete_user= Session()
if request.method == "POST":
    user_id = request.form['user_list']
    try :
        num_rows_deleted_map = session_delete_mapping.query(UserRoleMapping).filter(UserRoleMapping.user_id == user_id).delete()
        num_rows_deleted_user = session_delete_user.query(UserRoleMapping).filter(User.id == user_id).delete()
        session_delete_mapping.commit()
        session_delete_user.commit()
        User.query.filter(User.id == user_id).delete()
        flash("Successfully deleted !!")
    except InternalError as e:
        # mysql error code of 'lock timeout'
        if e.orig[0] == 1205:
            # call this handler again with same arguments
        else:
            flash("Oops something went wrong : "+ str(e))
            session_delete_mapping.rollback()
            session_delete_user.rollback()
    except Exception as e:
        flash("Oops something went wrong : "+ str(e))
        session_delete_mapping.rollback()
        session_delete_user.rollback()
return render_template('index.html')

请勿忘记导入抓取from sqlalchemy.exc import InternalError

的异常类

通常情况下,你可以很少得到这个例外,但如果没有,你应该检查你的服务器是否存在巨大或“停滞不前”#34;查询并优化它们。 粗略的你可以在myslq配置文件中增加wait_timeout