我正在尝试使用 Spring JDBCTemplate 从我的 mysql 数据库表中获取值的总和。
当特定查询的表中没有任何相关数据时,我得到一个空指针异常。 这是我的代码;
try {
String sql = "SELECT SUM(paid_value) FROM all_delay_payments_breakdown WHERE customer_order_id = '"+customerOrderId+"' AND installment_no = '"+i+"'";
partialTot = getSimpleJdbcTemplate().queryForObject(sql, Double.class);
tot = tot + partialTot ;
} catch (Exception e) {
System.out.println("Exception: While calculation partial tot for customer order id :"+customerOrderId+" and instlmnt nmbr : "+i+" = "+e);
}
我需要检查查询返回的值,然后如果为null,则将0添加到tot
中,否则将查询执行返回的值添加到变量中总计
。
但是我无法在这段代码之后检查返回值是否为空。
partialTot = getSimpleJdbcTemplate().queryForObject(sql, Double.class);
如果返回值为空,代码将不会继续。 (由于查询执行代码抛出空指针异常,因此执行直接进入catch
子句)
那我该怎么做呢?我正在寻找这样的东西
if(partialTot == null ){
tot = tot + 0;
}else{
tot = tot+ partialTot;
}
谢谢!
最佳答案
你可以使用coalesce
,如果sum
返回null
,它将返回0
:
select coalesce(sum(paid_value), 0) from <...>
关于mysql - Spring JDBCTemplate NULL 检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30002643/