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一起工作?马克???
答案 0 :(得分:6)
问题可能出在这一部分:
'? days'
问号在文字字符串中,因此sql解析器无法识别。 您可以尝试使用字符串连接运算符重写它,尽管在这种情况下我不是100%确定它是有效的语法。
根据this page on the postgres wiki,你应该能够简单地省略字符串'days',因为添加日期和整数被解释为添加指定的天数。
BETWEEN now()::date AND now()::date + ?
答案 1 :(得分:5)
重写SQL部分
AND weather.date BETWEEN now()::date AND (now() + '? days')::date
作为
AND weather.date BETWEEN now()::date AND ?
并使用值java.sql.Date
值而不是days
设置它。
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, days);
Date endDate = new Date(calendar.getTimeInMillis());
// ...
(再一次,它是java.sql.Date
,而不是java.util.Date
!)
答案 2 :(得分:0)
错误是说你在第一个sql语句中只有1个参数(即一个?),但是你传入两个参数。 Spring不知道如何处理第二个arg。