如何正确执行具有日期条件的 JdbcQuery?

How to correctly perform a JdbcQuery that have a date as where condition?

我正在使用 JdbcTemplate 开发一个 Spring 应用程序,我有以下疑问:

我必须实现一个执行以下简单查询的方法:

select * from CoefficienteRendimento 
where DataRendimento = '2015-08-01 00:00:00'

其中 DataRendimento 字段的值可以更改。

所以我正在做这样的事情:

public BigDecimal getRendimentoLordoCertificato(XXX) {

    String sql = "select * from CoefficienteRendimento where DataRendimento =  ?";

    .......................................................................
    .......................................................................
    .......................................................................


}

所以我的疑问是:

对于这种情况,最好将字符串值作为 XXX 参数(必须在查询中使用)传递为 '2015-08-01 00:00:00' 或表示此日期的 Date 对象?

使用 PreparedStatement.

Date yourDate = ...
Connection conn = ...

String sql = "select * from CoefficienteRendimento where DataRendimento =  ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setDate(1, yourDate);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
    ... // Handle your resultSet
}

更新的答案知道结果应该是一个(最多)BigDecimal 并且使用 Spring JDBC。

使用 jdbcTemplate,并且知道有 0 个或 1 个结果,并且您想获得有效结果或 null:

public BigDecimal getRendimentoLordoCertificato(Date currentDate) {

    String sql = "select Coefficiente_12 from CoefficienteRendimento where DataRendimento =  ?";

    List<BigDecimal> rendicontoLordoCert = getJdbcTemplate().query(
            sql, new Object[] { currentDate }, BigDecimal.class);

    if (rendicontoLordoCert.size > 0) {
        return rendicontoLordoCert.get(0);
    }
    return null;
}

您可以尝试在 pareparedStmt 中明确指定日期。

ps.addValue("yourDate", new java.util.Date(), java.sql.Types.DATE);

我正在使用Spring JdbcTemplate class所以解决方案是:

public BigDecimal getRendimentoLordoCertificato(Date currentDate) {

    String sql = "select Coefficiente_12 from CoefficienteRendimento where DataRendimento =  ?";

    BigDecimal rendicontoLordoCert = getJdbcTemplate().queryForObject(
            sql, new Object[] { currentDate }, BigDecimal.class);

    return rendicontoLordoCert;

}