postgresql 为什么即使没有插入新行,executeUpdate 也会返回 1?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15945754/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
why does executeUpdate return 1 even if no new row has been inserted?
提问by Sanyifej?
here is my very simple table (Postgres):
这是我的非常简单的表(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.
但是,如果我想通过 JDBC 插入一个字符串,则不会插入任何内容,尽管 prepareStatement.executeUpdate() 总是返回 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.
下面是我的方法,应该有效,但没有。如果我遗漏了一些明显的东西,请告诉我。我想补充一点,我从未收到任何 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);
}
}
}
}
回答by Sanyifej?
that was missing:
缺少的是:
conn.commit();
(after the executeUpdate())
(在 executeUpdate() 之后)
actually a new row was inserted but the DB rolled back immediately.
实际上插入了一个新行,但数据库立即回滚。
回答by Jan Piel
executeupdate is for a 'update table set column = value so on'. For insert just call execute of PreparedStatement.
executeupdate 用于“更新表集列 = 值等”。对于插入,只需调用 PreparedStatement 的执行。