A little bit confused - lets say we create InitialContext
and DataSource
like this:
InitialContext ctx = new InitialContext();
DataSource ds = ((DataSource) ctx.lookup("jdbc/hsqldb"));
Now when some database operations are made, I suggest ctx
should be closed:
if (ctx != null) {
ctx.close();
}
But here InitialContext
is simply initialised to 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;
}
So what is happening when ctx
is initiliased to null
without closing it?