Jdbctemplate query for string: EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0

前端 未结 17 1215
执笔经年
执笔经年 2020-11-29 16:22

I am using Jdbctemplate to retrieve a single String value from the db. Here is my method.

    public String test() {
        String cert=null;
        Strin         


        
17条回答
  •  -上瘾入骨i
    2020-11-29 17:15

    In JdbcTemplate , queryForInt, queryForLong, queryForObject all such methods expects that executed query will return one and only one row. If you get no rows or more than one row that will result in IncorrectResultSizeDataAccessException . Now the correct way is not to catch this exception or EmptyResultDataAccessException, but make sure the query you are using should return only one row. If at all it is not possible then use query method instead.

    List strLst  = getJdbcTemplate().query(sql,new RowMapper {
    
      public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
            return rs.getString(1);
      }
    
    });
    
    if ( strLst.isEmpty() ){
      return null;
    }else if ( strLst.size() == 1 ) { // list contains exactly 1 element
      return strLst.get(0);
    }else{  // list contains more than 1 elements
      //your wish, you can either throw the exception or return 1st element.    
    }
    

提交回复
热议问题