connection object close()无法正确关闭连接

8cdiaqws  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(437)

我正在使用以下代码片段连接数据库

private Connection getConnection(JspWriter out, String host, String dbname,
        String port, String user, String pwd) {
    try {
        if (host == null || dbname == null) {
            throw new IllegalArgumentException("Invalid host or dbname"); 
        }
        String url = "jdbc:mysql://" + host + ":" + port + "/" + dbname; 
        String clazz = "org.gjt.mm.mysql.Driver"; 
        Driver driver = (Driver) Class.forName(clazz).newInstance();
        DriverManager.registerDriver(driver);
        return DriverManager.getConnection(url, user, pwd);
    } catch (Exception e) {
       System.out.println("Exception occured while get connection :"+ e);
   }
    return null;
}

一旦查询被执行,我就关闭连接对象

private JSONArray executeQuery(JspWriter out, Connection connection,String query, Object[] params) throws Exception {

PreparedStatement st = null;
ResultSet rs = null;
try {
    //connection = getConnection();
    st = connection.prepareStatement(query);
    int c = 1;
    for (Object param : params) {
        st.setObject(c++, param);
    }
    rs = st.executeQuery();
    if (rs == null) {
        return null;
    }
    ResultSetMetaData meta = rs.getMetaData();
    List<String> columns = getColumnNames(meta);
    JSONArray json = new JSONArray();
    while (rs.next()) {
        JSONObject obj = new JSONObject();
        for (String column : columns) {
            obj.put(column, rs.getObject(column));
        }
        json.put(obj);
    }
    return json;
} catch (Exception e) {
        System.out.println("Exception occurred while execute query" + e);
} finally {
    try {
        if (rs != null) {
            rs.close();
        } 
    } catch(Exception ex) {
            //Print exception
    }
    try {
        if (st != null) {
            st.close();
        }
    } catch(Exception ex) {
            //Print exception
    } 
    try {
        if(connection != null) {
                connection.close();
        }
        if(connection.isClosed()) {
            connection = null;
            }
        } catch(Exception ex) {
                //Print exception
        }
    }
    return null;
  }

虽然我和 .close() 方法。我要确保连接已关闭 connection.closed() 它返回true—表示连接已成功关闭。
一旦连接限制达到最大值-我会 DB Connection Exhausted 我的服务器无法建立进一步的连接。
有人能帮我进一步调试一下吗。

k4aesqcs

k4aesqcs1#

没有严格的联系。对资源使用try

开始使用try with resources语法,它是在java 7中引入的:

try (Connection connection = getConnection();
     PreparedStatement st = connection.prepareStatement(query)) {

    // ...
    try (ResultSet rs = st.executeQuery()) {

        // ...
    }
}

它更方便,更不容易出错。

谁的责任是关闭连接?

关闭连接的责任总是与打开连接的逻辑有关。如果您的方法无法获取连接,则不应关闭该连接。调用者应该(你还没有发布他的逻辑)。理想情况下,您无论如何都应该使用连接池,但这可能与本文的主题无关。
举个例子:

// This logic opens the connection by calling getConnection()
// It must also close the connection again, e.g. with try-with-resources
try (Connection connection = getConnection()) {
  doSomething(connection);
}

...
// This logic didn't open a connection. It receives it from someone else
// It mustn't close the connection!
void doSomething(Connection connection) {

  // But if other resources are opened, then they must be closed here:
  try (Statement stmt = connection.createStatement()) {
    doSomething(stmt);
  }
}

..
// Again, this method didn't open the statement, it shouldn't close it
void doSomething(Statement statement) {
  ..
}

相关问题