繁体   English   中英

由于“超过了锁定等待超时,导致事务失败; 尝试重新开始交易”

[英]Transactions fails due to “Lock wait timeout exceeded; try restarting transaction”

尝试更新某个表时,它失败,但以下情况除外:“超出了锁定等待超时;尝试重新启动事务”。 一些信息:我有两个表,profile和profile_units。 ID是概要文件表的主键,ID是profile_units中的主键的一部分,也是概要文件中ID的外键。 我调用saveProfileChanges时,updateAllFields方法成功,但是addStmt.executeUpdate();成功。 在handleActivityUnitsChanges中失败,但出现上述异常。 我使用MySQL v5.0作为数据库。 我究竟做错了什么?

我尝试执行以下代码:

    public static Profile saveProfileChanges(Profile profile, List unitsToAdd)
        throws Exception
{
    Connection con = null;
    try
    {
        con = ConnectionManager.getConnection();

        updateAllFields(con, profile);

        handleActivityUnitsChanges(con, profile, unitsToAdd);

        con.commit();
        return profile;
    }
    finally
    {
        ConnectionManager.closeConnection(con);
    }
}

private static void handleActivityUnitsChanges(Connection con, Profile profile, List<ActivityUnit> unitsToAdd) throws Exception
{
    PreparedStatement addStmt = null;

    try
    {
        for (ActivityUnit currentUnitToAdd : unitsToAdd)
        {
            String sqlStatement = "insert into profile_units (ID, ActivityUnit) values (?, ?)";
            addStmt = con.prepareStatement(sqlStatement);

            addStmt.setLong(1, profile.getId());
            addStmt.setLong(2, currentUnitToAdd.getId());

            System.out.println(sqlStatement);

            addStmt.executeUpdate();
            addStmt.close();
        }
    }
    catch (Exception e)
    {
        con.rollback();
        throw e;
    }
    finally
    {
        ConnectionManager.closeStatement(addStmt);
    }
}

public static Connection getConnection() throws Exception
{
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    Connection con = DriverManager.getConnection("jdbc:mysql:///someproject", "a", "a");

    con.setAutoCommit(false);

    return con;
}

好的,我发现了问题所在-在updateAllFields中(出于某种奇怪的原因,我没有在此处显示),我获得了一个新的连接,因此这两个事务混合在一起了。 感谢任何人的帮助!

看一下innodb_lock_wait_timeout变量。 这是-InnoDB事务在回滚之前可能等待锁定的超时时间(以秒为单位) 默认值为50秒,您可以增加此值; 但我认为最好重写循环插入代码或进行优化。

作为一种变体-尝试在事务中运行较少的插入语句。 为了加快交易,您可以使用多个插入,例如-'INSERT INTO table1(column1,column2)VALUES(1,'text1'),(2,'text2')...;'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM