无论数据库中的数据如何,Spring jdbcTemplate查询始终返回null

时间:2016-09-07 18:56:26

标签: sql spring jdbctemplate

我需要根据日期范围从数据库中获取总和值。我尝试以下列方式使用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时,它工作正常。我假设我发送的选择参数有问题。

date和todate都是格式08/09/2016格式前端的字符串值。

1 个答案:

答案 0 :(得分:2)

SQL正在使用命名参数,但代码正在发送参数列表。使用NamedParameterJdbcTemplate并更改您在参数中传递的方式,或使用JdbcTemplate并更改SQL以使用?占位符而不是命名参数。

如果使用NamedParameterJdbcTemplate,则必须在SQL中按名称引用参数,并且在传递参数时必须提供名称。将它们放在地图中(如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"

并将其余部分留下。

相关问题