重用PreparedStatement时可能出现资源泄漏?

bkn*_*per 6 java database resources jdbc

假设您有以下代码:

    Connection connection = null;
    PreparedStatement ps = null;

    try {
        Connection = connectionFactory.getConnection();

        ps = statement.prepareStamement(someQuery);
        // execute and read and stuff

        // now you want to use the ps again, since you don't want ps1, ps2, ps3, etc.
        ps = statement.prepareStatement(someOtherQuery); // DOES THIS FORM A POTENTIAL LEAK?
    } catch (a lot of exceptions) {
        // process exceptions
    } finally {

        // close the resources (using util class with null-checks and everything)
        SomeUtilClass.close(ps);
        SomeUtilClass.close(connection);
    }
Run Code Online (Sandbox Code Playgroud)

是否重复使用ps变量潜在泄漏?

如果是这样,我会讨厌声明多个这样的预处理语句(ps1,ps2,ps3等).我该怎么重构呢?

想什么?

编辑

收到几个答案,说明这无关紧要.我想指出的是,我正在经历一个开放时间过长的开放游标,并且想知道这种模式是否与它有关.

我的想法是:

第一个语句被取消引用并且GC',所以在这个例子中第一个PreparedStatement如何关闭(数据库方式)?

das*_*ght 5

这不一定会产生经典的“永久”意义上的泄漏。垃圾收集器最终将到达准备好的语句的第一个实例,并调用其终结器。

但是,这不是让垃圾回收器处理释放潜在的关键资源(例如DB句柄)的好习惯:您应该close在重用已准备好的语句变量之前调用该方法,或者根本不要重用该变量。

try {
    Connection = connectionFactory.getConnection();

    ps = statement.prepareStamement(someQuery);
    // execute and read and stuff

    // now you want to use the ps again, since you don't want ps1, ps2, ps3, etc.
    // v v v v v v v v v v v
    SomeUtilClass.close(ps);
    // ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
    ps = statement.prepareStatement(someOtherQuery); // DOES THIS FORM A POTENTIAL LEAK?
} catch (a lot of exceptions) {
    // process exceptions
} finally {

    // close the resources (using util class with null-checks and everything)
    SomeUtilClass.close(ps);
    SomeUtilClass.close(connection);
}
Run Code Online (Sandbox Code Playgroud)