-2

有点困惑 - 假设我们创建InitialContextDataSource喜欢这样:

InitialContext ctx = new InitialContext();
DataSource ds = ((DataSource) ctx.lookup("jdbc/hsqldb"));

现在进行一些数据库操作时,我建议ctx应该关闭:

 if (ctx != null) {
     ctx.close();
    }

这里 InitialContext只是简单地初始化为null

import java.sql.*;
import javax.sql.*;
import javax.ejb.*;
import javax.naming.*;

public class DistributedTransactionBean implements SessionBean {

    // ...

    public void ejbCreate() throws CreateException {

        ctx = new InitialContext();
        ds = (DataSource)ctx.lookup("jdbc/distCoffeesDB");
    }

    public void updateTotal(int incr, String cofName, String username,
                            String password)
        throws SQLException {

        Connection con;
        PreparedStatement pstmt;

        try {
            con = ds.getConnection(username, password);
            pstmt = con.prepareStatement("UPDATE COFFEES " +
                        "SET TOTAL = TOTAL + ? " +
                        "WHERE COF_NAME = ?");
            pstmt.setInt(1, incr);
            pstmt.setString(2, cofName);
            pstmt.executeUpdate();
            stmt.close();
        } finally {
            if (con != null) con.close();
        }
    }

    private DataSource ds = null;
    private Context ctx = null;
}

那么在ctx没有null关闭它的情况下会发生什么?

4

1 回答 1

1

你什么时候认为“ctx 设置为空”?

从您提供的代码来看,ctx 没有“设置为 null”,它被初始化为 null。

然后(在初始化之后)在创建 bean 期间,调用 ejbCreate() 并分配对 InitialContext 的引用:

ctx = new InitialContext();

于 2017-08-03T09:56:24.403 回答