why does executeUpdate return 1 even if no new row

2019-02-25 04:53发布

here is my very simple table (Postgres):

CREATE TABLE IF NOT EXISTS PERFORMANCE.TEST
(
test text NOT NULL UNIQUE
);

if I try to insert a String using the command below FROM the database,everything works as expected, not surprisingly a new row appears in the DB.

insert into performance.test (test) values ('abbbbaw');

However if I want to insert a String through JDBC, nothing gets inserted, although preparedStatement.executeUpdate() always returns 1.

Below is my method that should be working but it does not. Please tell me if I am missing something obvious. I want to add that I never get any SQLException.

private void storePerformance() {
    Connection conn= initializePerformanceConnection();
    if (conn!= null) {
       PreparedStatement insertPS = null;
        try {
            insertPS = conn.prepareStatement("insert into performance.test (test) values (?)");
            insertPS.setString(1, queryVar);
             int i = insertPS.executeUpdate();
            LogManager.doLog(LOG, LOGLEVEL.INFO," numberofrows= "+i);

        }  catch (SQLException e) {
            LogManager.doLog(LOG, LOGLEVEL.INFO,"Inserting query failed = "+queryVar,e);
        }finally{
            if(insertPS != null){
                try {
                    insertPS.close();
                } catch (SQLException e) {
                    LogManager.doLog(LOG, LOGLEVEL.INFO,"Closing PreparedStatement failed = "+queryVar,e);
                }
            }
            try {
                conn.close();
            } catch (SQLException e) {
                LogManager.doLog(LOG, LOGLEVEL.INFO,"Closing performanceConnection failed= "+ queryVar, e);
            }
        }           
    }
}

2条回答
迷人小祖宗
2楼-- · 2019-02-25 05:31

that was missing:

conn.commit();

(after the executeUpdate())

actually a new row was inserted but the DB rolled back immediately.

查看更多
SAY GOODBYE
3楼-- · 2019-02-25 05:46

executeupdate is for a 'update table set column = value so on'. For insert just call execute of PreparedStatement.

查看更多
登录 后发表回答