jdbc连接数据库时,先获取connection,再通过statement进行操作,将结果集放在resultset中,不过在关闭数据库的时候要小心,要跟前面的操作反着来,不然就会出现异常。如果直接关闭connection的话,就是说将其他也关闭了,再对其他的如statement进行操作就会出现:操作不允许在关闭以后进行的异常。
try { rs = stmt.executeQuery(sql); } catch (SQLException e) { System.out.println("execute query in findUserByEmail failed"); e.printStackTrace(); } finally { stmt.close(); conn.close(); } if (rs.next()) { User user = new User(); user.setUserId(rs.getLong(1)); user.setName(rs.getString(2)); user.setEmail(rs.getString(3)); user.setPassword(rs.getString(4)); rs.close(); return user; } else { rs.close(); return null; }
正确的应该按顺序来进行:
try { rs = stmt.executeQuery(sql); } catch (SQLException e) { System.out.println("execute query in findUserByEmail failed"); e.printStackTrace(); } if (rs.next()) { User user = new User(); user.setUserId(rs.getLong(1)); user.setName(rs.getString(2)); user.setEmail(rs.getString(3)); user.setPassword(rs.getString(4)); rs.close(); stmt.close(); conn.close(); return user; } else { rs.close(); stmt.close(); conn.close(); return null; }