当出现上述报错时,请继续查看本文
private static Connection connection = null;
private static PreparedStatement preStmt = null;
private static ResultSet result = null;
private static Connection getConnection() throws NamingException, SQLException {
Context context = new InitialContext();
DataSource ds = (DataSource)context.lookup("java:comp/env/MySQL");
return ds.getConnection();
}
private static PreparedStatement createPrepareStatement(String sql, Object[] params) throws ClassNotFoundException, SQLException, NamingException {
PreparedStatement preStmt = null;
preStmt = getConnection().prepareStatement(sql);
if (params != null) {
for (int i = 0; i < params.length; i++) {
preStmt.setObject(i + 1, params[i]);
}
}
return preStmt;
}
private static void closeAll(ResultSet rs, Statement stmt, Connection connection) {
try {
if (rs != null)
rs.close();
if (stmt != null)
stmt.close();
if (connection != null)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
经仔细阅读发现,getConnection生成的Connection没有给connection变量,导致closeAll中的if (connection!=null)始终处于不执行的状态,connection.close()一直没有执行。多次获取Connection,使得connection不能再被获取。