Jaa*_*nus 3 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);
}
Run Code Online (Sandbox Code Playgroud)
错误:
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.
Run Code Online (Sandbox Code Playgroud)
它适用于:
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);
}
Run Code Online (Sandbox Code Playgroud)
所以问题是当我使用两个?在我的查询中标记.我怎样才能让它与2一起工作?分数???
问题可能出在这一部分:
'? days'
Run Code Online (Sandbox Code Playgroud)
问号在文字字符串内,因此sql解析器无法识别. 您可以尝试使用字符串连接运算符重写它,尽管在这种情况下我不是100%确定它是有效的语法.
根据postgres wiki上的这个页面,您应该能够简单地省略字符串'days',因为添加日期和整数被解释为添加指定的天数.
BETWEEN now()::date AND now()::date + ?
Run Code Online (Sandbox Code Playgroud)
重写SQL部分
AND weather.date BETWEEN now()::date AND (now() + '? days')::date
Run Code Online (Sandbox Code Playgroud)
如
AND weather.date BETWEEN now()::date AND ?
Run Code Online (Sandbox Code Playgroud)
并设置一个值得一提的java.sql.Date
值而不是days
.
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, days);
Date endDate = new Date(calendar.getTimeInMillis());
// ...
Run Code Online (Sandbox Code Playgroud)
(再说一遍java.sql.Date
,不是java.util.Date
!)
归档时间: |
|
查看次数: |
4351 次 |
最近记录: |