我有以下代码:
static ArrayList<PreparedStatement> alPrepStmts = new ArrayList<PreparedStatement>();
static PreparedStatement m_stmtOne;
static PreparedStatement m_stmtTwo;
static PreparedStatement m_stmtThree;
...
static PreparedStatement m_stmtOneHundred;
private static void init() {
alPrepStmts.add(m_stmtOne);
alPrepStmts.add(m_stmtTwo);
alPrepStmts.add(m_stmtThree);
...
alPrepStmts.add(m_stmtOneHundred);
}
private static void work() {
if(m_stmtOne == null) {
// assign m_stmtOne
}
// use m_stmtOne
}
private static void close() throws SQLException {
for(PreparedStatement ps : alPrepStmts) {
if(ps != null) {
ps.close();
ps = null;
}
}
}
init()函数只会被调用一次。work()和close()函数可能会被多次调用。问题在于,在调用close()函数之后,PreparedStatements并没有被设置为null。下一次调用work()函数时,m_stmtOne不是null,但是已经关闭了。我想我可以检查m_stmtOne是否打开,但是我想知道如何将容器的成员赋值为null。
我还尝试使用迭代器,但也不起作用。下面的if条件永远不会成立。
private static void ClosePreparedStatements() throws SQLException {
for(Iterator<PreparedStatement> it = alPrepStmts.iterator(); it.hasNext();) {
PreparedStatement ps = (PreparedStatement)it.next();
if(ps != null) {
ps.close();
ps = null;
}
}
}
我知道我可以手动关闭和分配每个语句,但我只是想知道将null分配给容器中的元素的最佳方法是什么。
init()
方法仅用100个null
条目填充alPrepStatements
。 - Stephen C