Spring JDBCTemplate NULL 检查
Spring JDBCTemplate NULL check
我正在尝试使用 Spring JDBCTemplate 从我的 mysql 数据库 table 中获取值的总和。
当特定查询的 table 中没有任何相关数据时,我得到一个空指针异常。
这是我的代码;
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
,否则将查询执行返回的值添加到变量tot
.
但是我无法在这段代码之后检查返回值是否为空。
partialTot = getSimpleJdbcTemplate().queryForObject(sql, Double.class);
如果返回值为空,代码将不会继续。 (由于查询执行代码抛出空指针异常,因此执行直接进入catch
子句)
那我该怎么做呢?我正在寻找这样的东西
if(partialTot == null ){
tot = tot + 0;
}else{
tot = tot+ partialTot;
}
谢谢!
您可以使用 coalesce
,它将 return 0
如果 sum
returns null
:
select coalesce(sum(paid_value), 0) from <...>
我正在尝试使用 Spring JDBCTemplate 从我的 mysql 数据库 table 中获取值的总和。
当特定查询的 table 中没有任何相关数据时,我得到一个空指针异常。 这是我的代码;
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
,否则将查询执行返回的值添加到变量tot
.
但是我无法在这段代码之后检查返回值是否为空。
partialTot = getSimpleJdbcTemplate().queryForObject(sql, Double.class);
如果返回值为空,代码将不会继续。 (由于查询执行代码抛出空指针异常,因此执行直接进入catch
子句)
那我该怎么做呢?我正在寻找这样的东西
if(partialTot == null ){
tot = tot + 0;
}else{
tot = tot+ partialTot;
}
谢谢!
您可以使用 coalesce
,它将 return 0
如果 sum
returns null
:
select coalesce(sum(paid_value), 0) from <...>