在管理工作室和 executeUpdate
中工作的查询使相同的 executeUpdate
返回 -1
,这在我们的任何文档中都未定义可以找到。它应该只返回行数或0
。这是什么意思?如果这很重要,驱动程序就是 JDBC-ODBC 桥。
例子:
String query = "IF NOT EXISTS (SELECT * FROM animals WHERE animal_name ='" + a +"') INSERT INTO " + table + " (animal_name, animal_desc, species_id) VALUES ('" + a + "', '" + b + "', " + c + ")";
int result = statement.executeUpdate(query);
System.out.println(result);
查询有效,当行被添加到数据库时,它返回 -1 很奇怪,文档说它只会返回 0 或行数(我已经更正了)。
更新:
在 Management Studio 中运行此命令会导致“命令成功完成”。
IF NOT EXISTS (SELECT * FROM animals WHERE animal_name = 'a')
INSERT INTO animals(animal_name, animal_desc, species_id) VALUES ('a', 'a', 1)
这应该意味着该方法应该返回 0,因为它不返回任何内容,对吗?
最佳答案
由于执行的语句实际上不是DML(例如UPDATE
、INSERT
或EXECUTE
),而是一段T-SQL < em>包含 DML,我怀疑它没有被视为更新查询。
JDBC 4.1 规范的第 13.1.2.3 节陈述了一些事情(顺便说一句很难解释):
When the method
execute
returns true, the methodgetResultSet
is called to retrieve the ResultSet object. Whenexecute
returns false, the methodgetUpdateCount
returns an int. If this number is greater than or equal to zero, it indicates the update count returned by the statement. If it is -1, it indicates that there are no more results.
鉴于此信息,我猜 executeUpdate()
内部会执行 execute()
,然后 - 因为 execute()
将返回false
- 它将返回 getUpdateCount()
的值,在这种情况下 - 根据 JDBC 规范 - 将返回 -1
。
1) Statement.executeUpdate()
的 Javadoc 进一步证实了这一点。说:
Returns: either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing
还有 2) Statement.getUpdateCount() 的 Javadoc指定:
the current result as an update count; -1 if the current result is a ResultSet object or there are no more results
澄清一下:鉴于 executeUpdate()
的 Javadoc,该行为可能是错误的,但可以解释。
正如我在其他地方评论的那样,-1 可能只是表示:也许有些东西发生了变化,但我们根本不知道,或者我们无法给出准确的变化数量(例如,因为在这个例子中它是一 block 执行的 T-SQL)。
关于java - Statement.executeUpdate() 返回 -1 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12400985/