-1

我非常确定我正在关闭 finally 块中的 con,rs,stmt。但似乎在第 4 次尝试执行更新时出现“连接过多”错误。

public boolean setUserSettings(UserSettings userSettings)
{
    ResultSet rs = null;
    Connection con = null;
    PreparedStatement stmt = null;
    String _query;

    try
    {
        System.out.println("total current connections: " + dataSource.getActive());
        con = dataSource.getConnection();
        _query = Util.readIn("/sql/select/selectUserSettingsCount.sql", MySqlPersistence.class);
        stmt = con.prepareStatement(_query);
        stmt.setString(1, userSettings.user);

        rs = stmt.executeQuery();
        boolean found = rs.next() && rs.getInt(1) == 1;

        if (!found)
        {
            _query = Util.readIn("/sql/insert/setUserSettings.sql", MySqlPersistence.class);
            stmt = con.prepareStatement(_query);
            stmt.setString(1, userSettings.user);
            stmt.setBoolean(2, userSettings.isActive);
            stmt.setString(3, userSettings.phone);
            stmt.setString(4, userSettings.phone2);
            stmt.setString(5, userSettings.phone3);
            stmt.setString(6, userSettings.contact_strategy);
        }
        else
        {               
            _query = Util.readIn("/sql/update/updateUserSettings.sql", MySqlPersistence.class);
            stmt = con.prepareStatement(_query);
            stmt.setString(1, userSettings.phone);
            stmt.setString(2, userSettings.phone2);
            stmt.setString(3, userSettings.phone3);
            stmt.setString(4, userSettings.user);
        }

        int success = stmt.executeUpdate();
        if (found && success == 1)
        {
            return true;
        }
        else
        {                
            return false;
        }
    }
    catch (Exception e)
    {            
        e.printStackTrace();
        return false;
    }
    finally
    {
        try { if (rs != null) System.out.println("closing rs"); rs.close(); } catch (SQLException e) { }
        try { if (stmt != null) System.out.println("closing stmt"); stmt.close(); } catch (SQLException e) { }
        try { if (con != null) System.out.println("closing con"); con.close(); } catch (SQLException e) { }
    }
}
4

1 回答 1

3

您为每个方法调用创建 2 个语句,但只关闭 1 个。在进入第一个大块之前if,您应该关闭现有语句。

更新:

经过进一步思考,我注意到您的代码中存在另一个错误。这种模式被打破了:

if (con != null) System.out.println("closing con"); con.close();

事实上,这是一个很好的例子,说明了为什么你应该总是在 if 块中使用大括号。重新格式化,这段代码是:

if (con != null) 
    System.out.println("closing con"); 
con.close();

但是,您真正想要的是:

if (con != null) {
    System.out.println("closing con"); 
    con.close();
}
于 2013-02-04T16:54:23.930 回答