2011-04-29 72 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不知道如何處理第二個參數。