简体   繁体   English

java.sql.连接漏电问题

[英]java.sql.Connection leakage issue

I have a class which takes a database connection over constructor, as you can see from the sample code connCat = con_cat (con_cat is being passed in).我有一个 class ,它通过构造函数进行数据库连接,从示例代码connCat = con_cat中可以看出(正在传入 con_cat)。

Please let me know: do I need to explicitly close the connCat connection inside this class, so the connection will be released properly?请让我知道:我是否需要明确关闭此 class 内部的 connCat 连接,以便正确释放连接?

If it's missing, will it cause connection leakage?如果丢失,是否会导致连接泄漏?

Will having a finally clause and doing connCat.close();将有一个 finally 子句并执行connCat.close(); and connCat = null;connCat = null; be enough?足够?

public class GenericDbProc extends DBProcessor {
Logger fileLogger = Logger.getLogger(GenericDbProc.class);
Connection connCat;

public GenericDbProc(Connection con_cat)
{
    connCat = con_cat;
}

public List<MxsCustomParam> getServiceEndPointDetails(String module_name) {
    StringBuffer sb = new StringBuffer();
    PreparedStatement stmt = null;
    ResultSet rs = null;
    
    sb.append("select xxxxxxx ")
            .append(" where module = ?");
    List<MxsCustomParam> mxsCustomParamList = new ArrayList<MxsCustomParam>();

    try {
        stmt = connCat.prepareStatement(sb.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        stmt.setString(1, module_name);
        
        rs = stmt.executeQuery();

You get the connection passed over the constructor from the outside.您从外部通过构造函数获取连接。 I'd say that closing the connection should not be managed here, but on the outside too.我想说关闭连接不应该在这里进行管理,而应该在外部进行。

And yes, the connection should be closed once it is not needed any more, as it holds a socket open in the background and there is a limit to how many connections you can open.是的,一旦不再需要连接就应该关闭它,因为它在后台保持一个打开的套接字,并且可以打开多少个连接是有限的。 If you simply release the reference to this object, then finalize should be called and close the connection at a point of time automaticaly, but it is considered bad practice to rely on this behaviour.如果您只是简单地释放对此 object 的引用,则应调用 finalize 并在某个时间点自动关闭连接,但依赖此行为被认为是不好的做法。

And yes, connections are closed in a finally block by calling the close method, but since Java 7 there are better ways to do that.是的,通过调用 close 方法在 finally 块中关闭连接,但是由于 Java 7 有更好的方法可以做到这一点。 Please look at this: Closing Database Connections in Java请看这个: Java 中的关闭数据库连接

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

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