我正在使用 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;
}
关于java - 如何正确执行以日期为条件的 JdbcQuery?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39096752/