2012-02-11 4 views
2

"시간대가없는 시간"데이터 유형이있는 테이블이 postgres 데이터베이스에 있으며 준비 문을 사용하여 삽입하려고 할 때 구문 오류가 발생합니다. 웹 페이지에서 입력을 사용하는 대신 새 java.sql.Time 객체를 만들려고했지만 여전히 동일한 오류가 발생합니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까?JDBC를 사용하여 PostgreSQL 시간 유형에 삽입하는 중 오류가 발생했습니다.

오류 :

org.postgresql.util.PSQLException: ERROR: invalid input syntax for type time: "1970-01-01 +01:00:00" 

테이블 :

         Table "public.reservation" 
    Column |   Type   |       Modifiers 
------------+------------------------+-------------------------------------------------------------- 
res_id  | integer    | not null default nextval('reservation_res_id_seq'::regclass) 
cust_id | character varying(50) | not null 
date  | date     | not null 
time  | time without time zone | not null 
num_people | integer    | not null 
Indexes: 
    "reservation_pkey" PRIMARY KEY, btree (res_id) 
Foreign-key constraints: 
    "reservation_cust_id_fkey" FOREIGN KEY (cust_id) REFERENCES customer(cust_id) 
Referenced by: 
    TABLE "reservation_table" CONSTRAINT "reservation_table_res_id_fkey" FOREIGN KEY (res_id) REFERENCES reservation(res_id) 

예약 자바 :

public static boolean createReservation(String custID, Date date, Time time, int numPeople) throws ServletException { 

    //TODO add checking 
    //TODO need to add determing table and if reservation time is free 

    boolean succeeded = false; 

    //checks if reservation is possible to be booked 
    if(checkReservationPossible()){ 

     //convet date to correct format for database 
     //SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy/MM/dd"); 
     //String formattedDate = dateFormatter.format(date); 

     //convert time to correct format for database 
     //SimpleDateFormat timeFormatter = new SimpleDateFormat("HH:mm"); 
     //String formattedTime = timeFormatter.format(time); 

     DatabaseAccess db = new DatabaseAccess(); 
     String sql = "INSERT INTO reservation (cust_id, date, time, num_people)" 
       + "VALUES (?,?,?,?)"; 

     LinkedList<Object> params = new LinkedList<Object>(); 
     params.add(custID); 
     params.add(date); 
     params.add(time); 
     params.add(numPeople); 

     succeeded = db.runUpdateQuery(sql,params); 

     db.close(); 
    } 

    return succeeded; 
} 

DB 액세스 자바 :

public boolean runUpdateQuery(String sql, LinkedList<Object> params) throws ServletException 
{ 
    // Using try {...} catch {...} for error control 
    try{ 
     // Create a statement variable to be used for the sql query 
     //Statement statement = this.connection.createStatement(); 

     // Perform the update 

     PreparedStatement pst = this.connection.prepareStatement(sql); 

     Iterator iter = params.iterator(); 

     for(int i = 1;iter.hasNext(); i++){ 
      Object curr = iter.next(); 
      //TODO may need to add more for different types 
      if(curr instanceof String){ 
       pst.setString(i, curr.toString()); 
      }else if (curr instanceof Integer){ 
       pst.setInt(i, (Integer)curr); 
      }else if (curr instanceof java.util.Date){ 
       //convert to sql date 
       java.util.Date tempDate = (java.util.Date)curr; 
       java.sql.Date sqlDate = new java.sql.Date(tempDate.getTime()); 
       pst.setDate(i, sqlDate); 
      }else if (curr instanceof Time){ 
       pst.setTime(i, Time.valueOf("11:30:00")); 
      } 
     } 

     int numRows = pst.executeUpdate(); 

     pst.close(); 

     if(numRows > 0){ 
      return true; 
     }else{ 
      return false; 
     } 
    } catch (SQLException e){ 
     // Deal with the error if it happens 
     throw new ServletException(String.format("Error: Problem running query... "), e); 
    } 
} 
+0

, 난 아무것도 볼 수 없습니다 :이 문제를 해결하는 좋은 방법은 내부적으로 PARAM 값으로 ?을 대체하기 위해 JDBC에서 사용하는 toString() 방법을 Time에서 파생 된 클래스를 생성하고 무시하는 것입니다 코드가 잘못되었습니다. 'java.sql.Time'을 가져오고 다른 클래스는 가져 오지 않도록하십시오. – Bohemian

답변

3

그 모든 검사가 필요하지 않습니다. 코드를 다음과 같이 간단히 변경하는 것이 좋습니다.

JDBC는 변환 할 필요가없는 다양한 일반적인 Java 유형을 처리 할 수 ​​있습니다.

사용자 정의 클래스를 사용하고 일부 JDBC 호환 유형을 가져 오려는 경우에만 유형을 확인해야합니다. 이것은 여기에 해당하지 않습니다.

+0

고마워요,하지만 삽입 시간 문제를 해결하지 못합니다. – Chris

+0

@Chris 시도해 보셨습니까? 또한 JDBC 드라이버가 데이터베이스 서버 버전에 적합한 버전입니까? 나는 포스트 그레스와 정확히 이것을 사용했기 때문에이 코드가 작동한다는 것을 안다. – Bohemian

+0

나는 시간 필드가없는 다른 테이블을 작성하여 올바르게 작성했다. 올바르게 작동한다. 서버의 버전을 모르지만 8.3-603을 사용하고 있습니다. – Chris

1

나는 자바가 단지 시간뿐만 아니라 날짜와 시간을 보내고 있다고 생각한다. 그것은 가치가 무엇인지에 대한

public class PosgreSqlTime inherits java.sql.Time 
{ 
    private static SimpleDateFormat SDF = new SimpleDateFormat("HH:mm:ss:SSS"); 
    @Override 
    public String toString() 
    { 
      return SDF.format(this); 
    } 
} 
+0

문자열로 설정할 수 없습니다. Time 객체를 기다리고 있습니다. – Chris

관련 문제