有人见过这个吗?我正在使用MS SQL Server 2008,并且我尝试使用两种不同的JDBC驱动程序(jtds和Microsoft)。我运行一个简单的语句来更新一行,它确实更新了它,但是getUpdateCount
返回0.如果我为不同的表尝试它,它会按预期返回1。这是关于这一张桌子的事情。
PreparedStatement ps =
conn.prepareStatement("select count(*) from foo_users where user_id = 1")
ResultSet rs = ps.executeQuery();
rs.next()
println(" count(*) is " + rs.getInt(1)); // Prints 1
ps = conn.prepareStatement("update foo_users set is_admin = 1 where user_id = 1")
ps.execute()
int count = ps.getUpdateCount()
println(" update count is " + count) // Prints 0. WTF.
造成这种情况的原因是什么?
更新以回复评论:是的,executeUpdate
有效。但我问这个问题是因为我使用的是名为jOOQ的查询库,它返回的结果不正确,因为它正在调用execute
和getUpdateCount
。我原本不提出这个问题,因为我认为这不是图书馆的错。
答案 0 :(得分:0)
您的更新语句需要“executeUpdate”。
executeUpdate返回rowcount。如果没有返回记录集,则“execute”只返回false,这不会有UPDATE。
答案 1 :(得分:0)
因此,关于同一件事,我现在面临一个非常奇怪的问题。任何线索将不胜感激- 因此,这是以前由其他开发人员编写的代码,对于Java和JDBC我还是比较陌生的
boolean getResultSet = cstmt.execute();
int updateCount = -1;
while (true) {
if (getResultSet) {
ResultSet r = cstmt.getResultSet();
while (r.next()) {}
r.close();
} else {
updateCount = cstmt.getUpdateCount();
if (updateCount != -1) {
// process update count if expected/wanted
}
}
if ((!getResultSet) && (updateCount == -1)) {
break; // done with loop
}
getResultSet = cstmt.getMoreResults();
}
我不知道这里到底发生了什么。
我有2个重复的DB,它们都托管在不同的服务器上。
相同的代码在一个DB上运行,而不在另一个DB上运行。
因此,在这里,execute()在两台服务器上都返回false,但是getUpdateCount()对于一台服务器返回0,而对于另一台服务器则返回1 / -1。
无法理解getUpdateCount()和execute()的确切作用。