JavaSpringJDBC模板问题
它与:JavaSpringJDBC模板问题,java,spring,jdbc,spring-mvc,Java,Spring,Jdbc,Spring Mvc,它与: 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.deg
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.
getWeather公共列表(int cityId,int days){
logger.info(“天:+天);
返回getSimpleJdbcTemplate().query(“选择weather.id、cities.name、weather.date、weather.degree”+
“从weather在weather.city\u id=cities.id上加入城市”+
“WHERE weather.city_id=?AND weather.date=now()::date”,
本文件为《城市地图绘制者》(cityId);
}
那么问题是当我使用两个时?在我的查询中有标记。
我怎样才能使它与2一起工作?标记???重写SQL部分
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);
}
作为
并将其设置为fullworthyjava.sql.Date
值,而不是days
AND weather.date BETWEEN now()::date AND ?
(再一次,它是
java.sql.Date
,而不是java.util.Date
!)错误是在第一条sql语句中只有一个参数(即a?),但您要传递两个参数。Spring不知道如何处理第二个参数。问题可能出在这部分:
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, days);
Date endDate = new Date(calendar.getTimeInMillis());
// ...
问号位于文本字符串中,因此sql解析器无法识别它。您可以尝试使用字符串连接运算符重写它,尽管我不能100%确定在本例中该语法是否有效
根据需要,您应该能够简单地省略字符串“days”,因为添加日期和整数被解释为添加指定的天数
'? days'
是的,但他们我必须做一个全新的方法或大量的代码..当psql已经有了增加天数的内置函数时。这真的是我唯一的解决办法吗。或者我们也可以让我的东西工作?它不允许使用preparedstatement占位符
?
作为SQL字符串/函数的一部分。它必须是全部价值。如果这是您的具体问题,只需创建一个帮助器方法来最小化代码重复。。运算符不存在:带有时区+整数的时间戳
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, days);
Date endDate = new Date(calendar.getTimeInMillis());
// ...
'? days'
BETWEEN now()::date AND now()::date + ?