遇到的NullPointerException

遇到的NullpointerException

为什么会出现空指针呢?

向我下面的代码:

   public User getLoginUser(Connection con, String userCode) throws Exception {
        ResultSet rs = null;
        User user = new User();
        // 确保连接上了数据库
        if (con!=null){
            String sql = "select * from `smbms_user` where userCode=?";
            Object[] params = {userCode}; // 这个userCode为参数传进来的值,setObject
            rs = jdbcUtil.excute(con, sql, params);
        }
        while(rs.next()){
            user.setId(rs.getInt("id"));
            user.setUserCode(rs.getString("UserCode"));
            user.setUserName(rs.getString("userName"));
            user.setUserPassword(rs.getString("userPassword"));
            user.setGender(rs.getInt("gender"));
            user.setBirthday(rs.getDate("birthday"));
            user.setPhone(rs.getString("phone"));
            user.setAddress(rs.getString("address"));
            user.setUserRole(rs.getInt("userRole"));
            user.setCreatedBy(rs.getInt("createdBy"));
            user.setCreationDate(rs.getTimestamp("creationDate"));
            user.setModifyBy(rs.getInt("modifyBy"));
            user.setModifyDate(rs.getTimestamp("modifyDate"));
        }
        jdbcUtil.release(null,null,rs);
        return user;
    }

原因是我实例化了一个User ,在查不到userCode的情况下也就不能赋值了,所以返回的user指向未知;就空指针了

改进:提示作用域并且都赋值为null。

public User getLoginUser(Connection connection, String userCode)
			throws Exception {
		// TODO Auto-generated method stub
		PreparedStatement pstm = null;
		ResultSet rs = null;
		User user = null;
		if(null != connection){
			String sql = "select * from smbms_user where userCode=?";
			Object[] params = {userCode};
			rs = BaseDao.execute(connection, pstm, rs, sql, params);
			if(rs.next()){
				user = new User();
				user.setId(rs.getInt("id"));
				user.setUserCode(rs.getString("userCode"));
				user.setUserName(rs.getString("userName"));
				user.setUserPassword(rs.getString("userPassword"));
				user.setGender(rs.getInt("gender"));
				user.setBirthday(rs.getDate("birthday"));
				user.setPhone(rs.getString("phone"));
				user.setAddress(rs.getString("address"));
				user.setUserRole(rs.getInt("userRole"));
				user.setCreatedBy(rs.getInt("createdBy"));
				user.setCreationDate(rs.getTimestamp("creationDate"));
				user.setModifyBy(rs.getInt("modifyBy"));
				user.setModifyDate(rs.getTimestamp("modifyDate"));
			}
			BaseDao.closeResource(null, pstm, rs);
		}
		return user;
posted @ 2021-04-02 14:06  能借我十块钱吗  阅读(61)  评论(0编辑  收藏  举报