【问题标题】:How to correctly perform a JdbcQuery that have a date as where condition?如何正确执行日期为 where 条件的 JdbcQuery?
【发布时间】:2023-03-12 06:07:02
【问题描述】:

我正在使用 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 对象?

【问题讨论】:

  • 一般来说最好使用日期,因为你不需要转换任何东西,这可能会出错。

标签: java spring jakarta-ee spring-jdbc jdbctemplate


【解决方案1】:

使用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;
}

【讨论】:

    【解决方案2】:

    您可以尝试在 parparedStmt 中显式指定日期。

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

    【讨论】:

    • addValue 不是 PreparedStatement 的方法
    【解决方案3】:

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

    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;
    
    }
    

    【讨论】:

    • 如果问卷要求的是 int,为什么要返回 BigDecimal?
    • 因为处理我的代码,我发现数据库上的 coumn 包含十进制值而不是整数
    • 所以问题是错误的。如果问题也如此正确,那么最终的其他答案将得到更正
    • 请注意,queryForObject 总是需要 1 个结果。如果您传递的日期没有结果,您的代码将生成异常
    • @DavideLorenzoMARINO Tnx,我会处理这种情况:-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-24
    • 1970-01-01
    • 2019-02-12
    • 1970-01-01
    • 2021-02-22
    • 1970-01-01
    • 2018-03-12
    相关资源
    最近更新 更多