SqlAlchemy + MySql 1205,'锁定等待超时;尝试重新启动事务'

b5lpy0ml  于 2023-05-05  发布在  Mysql
关注(0)|答案(2)|浏览(134)

我试图从User和UserRoleMapping两个表中删除一行。
使用User.id=〉UserRoleMapping.user_id将UserRoleMapping引用到User表。
我需要从两个表中删除一行使用用户特定的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 ',)

nnvyjq4y

nnvyjq4y1#

也许你可以使用重试包。

pip install retry
from sqlalchemy import exc

@retry(exc.OperationError, delay=5, tries=5)
def fun_name():
    try:
        #body of function
    except exc.OperationError:
        raise

当操作出错时,将重试5次,延时5秒

smtd7mpg

smtd7mpg2#

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

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时不要忘记导入异常类
通常情况下,你很少会遇到这种异常,但如果没有,你应该检查你的服务器是否有巨大的或“停滞”的查询,并优化它们。而粗你可以增加wait_timeout在myslq配置文件。

相关问题