why does executeUpdate return 1 even if no new row has been inserted?

微笑、不失礼 提交于 2019-12-20 01:41:52

问题


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

回答1:


that was missing:

conn.commit();

(after the executeUpdate())

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




回答2:


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



来源:https://stackoverflow.com/questions/15945754/why-does-executeupdate-return-1-even-if-no-new-row-has-been-inserted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!