Java Spring JDBC模板问题

标签 java spring jdbc spring-mvc

public List<Weather> getWeather(int cityId, int days) {
    logger.info("days: " + days);
    return getSimpleJdbcTemplate().query("SELECT weather.id, cities.name, weather.date, weather.degree " +
                                        "FROM weather JOIN cities ON weather.city_id = cities.id " +
                                        "WHERE weather.city_id = ? AND weather.date BETWEEN now()::date AND (now() + '? days')::date",
                                        this.w_mapper, cityId, days);
}

错误:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: PreparedStatementCallback; SQL [SELECT weather.id, cities.name, weather.date, weather.degree FROM weather JOIN cities ON weather.city_id = cities.id WHERE weather.city_id = ? AND weather.date BETWEEN now()::date AND (now() + '? days')::date]; The column index is out of range: 2, number of columns: 1.; nested exception is org.postgresql.util.PSQLException: The column index is out of range: 2, number of columns: 1.

它适用于:

public List<Weather> getWeather(int cityId, int days) {
    logger.info("days: " + days);
    return getSimpleJdbcTemplate().query("SELECT weather.id, cities.name, weather.date, weather.degree " +
                                        "FROM weather JOIN cities ON weather.city_id = cities.id " +
                                        "WHERE weather.city_id = ? AND weather.date = now()::date",
                                        this.w_mapper, cityId);
}

所以问题是当我使用两个时?我查询中的标记。 我怎样才能让它与 2 一起工作?标记???

最佳答案

问题可能出在这部分:

'? days'

问号位于文字字符串中,因此 sql 解析器无法识别它。 您可以尝试使用字符串连接运算符重写它,但我不能 100% 确定这种情况下的语法是否有效。

根据 this page on the postgres wiki您应该能够简单地省略字符串“days”,因为添加日期和整数会被解释为添加指定的天数。

BETWEEN now()::date AND now()::date + ?

关于Java Spring JDBC模板问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5832497/

相关文章:

页面上的 Spring MVC + Thymeleaf div 未生成

java - 如何清理 Log4j 中的日志消息以将它们保存在数据库中

java - 将Java连接到MySQL数据库

java - 保护 JDBC 连接时的证书和 keystore 配置

java - 如何设置共享首选项

java - 未接收 ApplicationEnvironmentPreparedEvent

java - Controller 方法上的自定义 validator

java - Spring JMSListener 和 JAXB 编码

java - 性能:从 HashMap.values() 创建一个 ArrayList

java - 在 Java 中四舍五入小数点后 2 位整数