java - 使用 JDBC 插入 PostgreSQL 时间类型时出错

标签 java postgresql jdbc time prepared-statement

我在 postgres 数据库中有一个数据类型为“time without time zone”的表,在尝试使用准备好的语句插入时出现语法错误。我已经尝试创建一个新的 java.sql.Time 对象而不是使用来自网页的输入,但我仍然遇到同样的错误。我做错了什么?

错误:

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)

预订Java:

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

数据库访问 Java:

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

最佳答案

您不需要所有这些检查。我建议您将代码简单地更改为:

for (int i = 1; iter.hasNext(); i++) {
    Object curr = iter.next();    
    pst.setObject(i, curr);
}

JDBC 知道如何处理所有各种常见的 java 类型 - 无需转换。

唯一需要检查类型的情况是,如果您想要使用一些自定义类,并且想从中获取一些 JDBC 兼容类型。这里不是这种情况。

关于java - 使用 JDBC 插入 PostgreSQL 时间类型时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9244211/

相关文章:

java - neo4j - 属性自动索引器不存储值

java - 为什么新建的Jhipster项目body height=0?

java - 字符串仅等于字符串的一部分

postgresql - 多个线程会导致约束集上的重复更新吗?

sql - 相同的值显示为三个值

java - 如何在没有heroku CLI的情况下获取数据库url等

java - 在Android Studio中构建多种口味时,找不到与包名称匹配的客户端

mysql - Postgresql 中 ELT() 函数的替代方法是什么?

带有sql语句的Java JDBC exec过程

java - 真正兼容 JDBC4 的 Oracle 驱动程序