【问题标题】:Exception handling during database operations数据库操作期间的异常处理
【发布时间】:2015-04-13 08:57:43
【问题描述】:

我有点想知道在下面的代码 sn-p 中,是否有可能没有关闭数据库连接。我在 SonarQube 中遇到问题,告诉“方法可能无法关闭数据库资源”

   try {       
        con = OracleUtil.getConnection();
        pstmtInsert = con.prepareStatement(insertUpdateQuery);
        pstmtInsert.setString(++k, categoryCode);
        pstmtInsert.clearParameters();
        pstmtInsert = con.prepareStatement(updateQuery);
        for (i = 0; i < userList.size(); i++) {
            pstmtInsert.setString(1, p_setId);
            addCount = pstmtInsert.executeUpdate();
            if (addCount == 1) {
                con.commit();
                usercount++;
            } else {
                con.rollback();
            }
        }
    }

    catch (SQLException sqle) {
        _log.error(methodName, "SQLException " + sqle.getMessage());
        sqle.printStackTrace();
        EventHandler.handle();//calling event handler
        throw new BTSLBaseException(this, "addInterfaceDetails", "error.general.sql.processing");
    }

    catch (Exception e) {
        _log.error(methodName, " Exception " + e.getMessage());
        e.printStackTrace();
        EventHandler.handle();//calling event handler
        throw new BTSLBaseException(this, "addInterfaceDetails", "error.general.processing");
    }

    finally {

        try {
            if (pstmtInsert != null) {
                pstmtInsert.close();
            }
        } catch (Exception e) {
            _log.errorTrace(methodName, e);
        }
        try {
            if (con != null) {
                con.close();
            }
        } catch (Exception e) {
            _log.errorTrace(methodName, e);
        }

        if (_log.isDebugEnabled()) {
            _log.debug("addRewardDetails", " Exiting addCount " + addCount);
        }
    }

提前致谢

【问题讨论】:

  • 我认为这对我来说看起来相当可靠。

标签: java exception-handling sonarqube


【解决方案1】:

当我在开始另一个准备语句之前关闭第一个准备语句时,问题已经解决。

在 pstmtInsert.clearParameters() 行之后添加下面的代码 sn -p;

    try {
            if (pstmtInsert != null) {
                pstmtInsert.close();
            }
        } catch (Exception e) {
            _log.errorTrace(methodName, e);
        }

【讨论】:

    【解决方案2】:

    如果您使用的是 Java 7+,我建议您使用try-with-resources。保证操作完成后资源关闭。

    【讨论】:

      猜你喜欢
      • 2017-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-12
      • 1970-01-01
      • 1970-01-01
      • 2013-04-01
      相关资源
      最近更新 更多