简体   繁体   中英

PostgreSQL cannot convert empty string to (null) date value

I will use JDBC to push Data into PostgreSQL .
So I wrote the Insert code like this in Dao.

public void insert(Connection con, List<InsertVo> list) throws Exception{
    PreparedStatement pstmt = null;
    int listSize = list.size();
    int pstmtSetInt = 1;

    try {
        String sql = "insert into tableName "
                + "(colName1,colName2,colName3) " 
                + "values ";
        String addInsertSql = "(?,?,?::date)";
        sql = addInsertQuery(sql, addInsertSql, listSize);
        pstmt = con.prepareStatement(sql);
        for (InsertVo vo : list) {
            pstmt.setString(pstmtSetInt++, vo.getColName1()); 
            pstmt.setInt(pstmtSetInt++, vo.getColName2());  
            pstmt.setString(pstmtSetInt++, vo.getColName3()); 
        }
        System.out.println(pstmt);

    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    } finally {
        try {
            if (pstmt != null) {
                pstmt.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

private String addInsertQuery(String sql, String addInsertSql, int listSize) {
    for (int idx = 0; idx < listSize; idx++) {
        sql = sql + addInsertSql;
        if (listSize-1 != idx) {
            sql = sql + ", ";
        }
    }
    return sql;
}

There are many Insert statements that are repeated when inputted once, so it was written while increasing the number of '()'.
The problem with this code, however, is that if the date part contains a null or an empty string like "" , you get an ERROR.
Since that part is not not null , it can be null or "" .
The bottom line is I want to know if there's something other than checking the date part and giving different insert statements.

The ERROR message looks like this.
org.postgresql.util.PSQLException: ERROR: invalid input syntax for type date: ""


I checked again and found that if I change the value to "" NULL, the ERROR does not go into it.

//pstmt.setString(pstmtSetInt++, vo.getColName3());

String dateValue=vo.getColName3();
if (dateValue.equals("")) {
        dateValue = null;
    }
pstmt.setString(pstmtSetInt++, dateValue);

Thank you for your help.

I want to know if there's something other than checking the date part and giving different insert statements.

You don't need to use a different SQL statement for each case, you just need to tweak the statement so that it won't fail when an empty string is passed:

INSERT INTO tblname ( ... , col3) VALUES ( ... , NULLIF(?, '')::date)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM