字符串的Jdbctemplate查询:EmptyResultDataAccessException:结果大小不正确:预期1,实际0 [英] Jdbctemplate query for string: EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0
问题描述
我正在使用Jdbctemplate从db中检索单个String值。这是我的方法。
I am using Jdbctemplate to retrieve a single String value from the db. Here is my method.
public String test() {
String cert=null;
String sql = "select ID_NMB_SRZ from codb_owner.TR_LTM_SLS_RTN
where id_str_rt = '999' and ID_NMB_SRZ = '60230009999999'";
cert = (String) jdbc.queryForObject(sql, String.class);
return cert;
}
在我的方案中,完全有可能不会对我的查询产生影响所以我的问题是如何解决以下错误消息。
In my scenario it is complete possible to NOT get a hit on my query so my question is how do I get around the following error message.
EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0
在我看来,我应该回到null而不是抛出异常。我怎样才能解决这个问题?在此先感谢。
It would seem to me that I should just get back a null instead of throwing an exception. How can I fix this? Thanks in advance.
推荐答案
在JdbcTemplate中, queryForInt
, queryForLong
, queryForObject
所有这些方法都希望执行的查询只返回一行。如果没有行或多行将导致 IncorrectResultSizeDataAccessException
。现在正确的方法是不捕获此异常或 EmptyResultDataAccessException
,但要确保您使用的查询应该只返回一行。如果根本不可能,则使用查询
方法。
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<String> 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.
}
这篇关于字符串的Jdbctemplate查询:EmptyResultDataAccessException:结果大小不正确:预期1,实际0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!