java - 查询结束后与数据库的连接未关闭

标签 java sql sql-server database prepared-statement

我执行了这个查询,但没有关闭连接,我不明白为什么。 这是显示连接数的屏幕截图(这就是为什么我知道连接未关闭) enter image description here

请帮我解决问题。

这是代码:

@Override
    public Map<MenuItem, Long> getGtinFromIngredientByLinkedProduct(Map<Long, MenuItem> ingredientIdProductMap) {
        Map<MenuItem, Long> result = new HashMap<MenuItem, Long>();
        String sql = "SELECT INGREDIENTS_GLOBAL_TRACK_IDF, INGREDIENT_ID FROM [PWRNXGDTA].INGREDIENTS WHERE INGREDIENT_ID in (";
        StringBuilder ingredientsIDs = new StringBuilder();
        boolean first = true;
        Set<Long> ingredients = ingredientIdProductMap.keySet();
        System.out.println("Ingredient id's SIZE: " + ingredients.size());
        for(Long ingredientId : ingredients) {
            if(!first){
                ingredientsIDs.append(",");
            } else {
                first = false;
            }
            ingredientsIDs.append(ingredientId);
        }
        sql+= ingredientsIDs+")";
        Connection con = null;
        PreparedStatement ps = null;
        QueryRunner q = null;
        ResultSet rs = null;
        try {
            q = super.getQueryRunner();
            con = q.getDataSource().getConnection();
            ps = con.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()) {
                result.put(ingredientIdProductMap.get(rs.getLong("INGREDIENT_ID")),
                        rs.getLong("INGREDIENTS_GLOBAL_TRACK_IDF"));
            }
        } catch (DAOException | SQLException e) {
            logger.info(e.getMessage());
        }
        finally {
            try {
                if(ps != null){
                    ps.close();
                }
                if(con != null) {
                    con.close();
                }
                if(q != null) {
                    q.getDataSource().getConnection().close();
                }
                if(rs != null) {
                    rs.close();
                }
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return result;
    }

有什么想法吗?

谢谢

最佳答案

在你的finally block 中,你没有创建一个新的连接吗?

if(q != null) {
    q.getDataSource().getConnection().close();
} 

QueryRunner 有一些 prepareConnection 方法和不同的close,您可以使用它们来简化处理。

关于java - 查询结束后与数据库的连接未关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42552041/

相关文章:

sql - 在 FULL OUTER JOIN 中选择非空列

java - linux top输出不现实?

java - 如何摆脱错误?

java - java中如何定义字符串数组中的特殊字符

mysql - 在 INSERT INTO 语句期间访问自动递增值

SQL 在 If 和 Else block 中插入临时表

sql - 在没有连接的情况下按行重复对查询结果进行排序

在指定日期之前显示的 SQL 查询

c# - 设计模式 : Polymorphism for list of objects

c# - SqlQuery 上的 Entity Framework 超时