2011-04-29 4 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); 
} 

오류 : 메신저 두를 사용하는 경우 자바 스프링 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 didnt work .. 연산자가 존재하지 않습니다 : 타임 스탬프가있는 타임 스탬프 + 정수 – Jaanus

+0

AWESOME !! 감사! – Jaanus

5

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

로서 SQL 부분을

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

다시 쓰기 및 days 대신 fullworthy java.sql.Date 값으로 설정

.

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

+0

SQL 문자열/함수의 일부로 preparedstatement 자리 표시 자'? '를 사용할 수 없습니다. 그것은 이미 모든 가치가 있어야합니다. 그것이 당신의 구체적인 문제라면 코드 중복을 최소화하는 헬퍼 메소드를 생성하십시오. – BalusC

0

오류가 첫 번째 SQL 문에 (예?) 만 1 PARAM을 가지고 말하고,하지만 당신은 두 개의 인수를 전달하는 . Spring은 두 번째 인수로 무엇을해야할지 모른다.