2011-04-29 118 views
3
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); 
} 

错误:的Java JDBC春季模板问题

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); 
} 

所以使用两个时,即时通讯的问题是:

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. 

它的工作原理?在我的查询中标记。 我如何使它与2一起工作?分数???

回答

6

的问题可能是在这一部分:

'? days' 

问号是字符串里面,所以它不被SQL分析器认可。 您可以尝试使用字符串连接运算符来重写它,尽管在这种情况下我不能100%确定这是有效的语法。

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

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

nope没有工作..操作员不存在:带时区+整数的时间戳 – Jaanus 2011-04-29 15:00:50

+0

真棒!谢谢! – Jaanus 2011-04-29 15:49:27

5

重写SQL部分

AND weather.date BETWEEN now()::date AND (now() + '? days')::date 

作为

AND weather.date BETWEEN now()::date AND ? 

并用fullworthy 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!)

+0

是的,但他们我必须做全新的方法或许多代码..当psql已经有builint功能添加天。这真的是我唯一的解决方案。或者我们可以让我的事情也工作? – Jaanus 2011-04-29 15:00:21

+0

不允许使用preparedstatement占位符''作为SQL字符串/函数的一部分。它已经成为整个价值。如果这是您的具体问题,只需创建一个帮助程序方法以尽量减少代码重复。 – BalusC 2011-04-29 15:15:42

0

错误是说,你只有1个参数(即?)在第一个SQL语句,但你传递有两个参数。 Spring不知道如何处理第二个参数。