我需要根据日期范围从数据库中获取总和值。我尝试通过以下方式使用 Spring jdbcTemplate 。但它不返回任何东西。
public void getTotal(String from, string toDate){
String totalSql="select sum(b.finalAmount) as total from example a, example b "+
"where a.created >= TO_TIMESTAMP(:fromDate, 'MM-DD-YYYY') AND a.created < TO_TIMESTAMP(:toDate, 'MM-DD-YYYY hh24:mi:ss') "+
"and a.tradein_id=b.tradein_id";
List<Integer> checkAmt = jdbcTemplate.query(sql, new RowMapper<Integer>() {
@Override
public Integer mapRow(ResultSet rs, int rowNum) throws SQLException
{
int check = rs.getInt("TOTAL");
return check;
}
}, fromDate,toDate);
int checkAmount = jdbcTemplate.queryForObject(
totalSql, new Object[]{fromDate, toDate},Integer.class);
}
当我在查询中硬编码 fromDate 和 toDate 时,它工作正常。我认为我发送的选择参数有问题。
起始日期和截止日期都是来自 08/09/2016 格式前端的字符串值。
最佳答案
SQL 使用命名参数,但代码发送参数列表。使用 NamedParameterJdbcTemplate 并更改传入参数的方式,或者使用 JdbcTemplate 并更改 SQL 以使用 ?
占位符而不是命名参数。
如果使用NamedParameterJdbcTemplate,则必须在SQL中按名称引用参数,并且在传入参数时必须提供名称。将它们放入 map 中,如下所示(来自 the spring-jdbc documentation ):
public int countOfActorsByFirstName(String firstName) {
String sql = "select count(*) from T_ACTOR where first_name = :first_name";
SqlParameterSource namedParameters = new MapSqlParameterSource("first_name", firstName);
return this.namedParameterJdbcTemplate.queryForObject(sql, namedParameters, Integer.class);
}
或者,您可以提供如下参数:
Map args = new HashMap();
args.put("fromDate", fromDate);
args.put("toDate", toDate);
jdbcTemplate.queryForObject(sql, args, Integer.class);
如果您不想使用命名参数,请将 SQL 更改为如下所示
String totalSql= "select sum(b.finalAmount) as total from example a, example b "+
"where a.created >= TO_TIMESTAMP(?, 'MM-DD-YYYY') AND a.created < TO_TIMESTAMP(?, 'MM-DD-YYYY hh24:mi:ss') "+
"and a.tradein_id=b.tradein_id"
剩下的就不用管了。
关于sql - Spring jdbcTemplate 查询始终返回 null,无论数据库中的数据如何,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39377277/