Java PreparedStatement.executeUpdate() 可以在插入时返回 0 吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18258891/
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
Can PreparedStatement.executeUpdate() ever return 0 on INSERT?
提问by Usman Mutawakil
Is there any condition under which a SQL INSERT statement executed with the method executeUpdate
on a PreparedStatement
object would return 0 without throwing an SQLException?
是否存在任何条件下executeUpdate
使用PreparedStatement
对象上的方法执行的 SQL INSERT 语句将返回 0 而不抛出 SQLException?
For example:
例如:
String query = "INSERT INTO mytable (column1,column2) VALUES (5,6)";
PreparedStatement preparedStatement = connection.prepareStatement(query);
if(preparedStatement.executeUpdate()!=1){
// A strange error has occurred
} else{
// do what ever
}
Why do I ask?I currently always check to ensure the number of rows returned is equal to 1 but I wonder if that is overkill if it should never return anything but 1.
我为什么要问?我目前总是检查以确保返回的行数等于 1,但我想知道如果它不应该返回除 1 之外的任何内容,这是否有点矫枉过正。
采纳答案by Sotirios Delimanolis
So I tried it and, yes, you can get a 0
return value with an INSERT
statement. This can happen if you SELECT * FROM
a table without rows INTO
another table. For example, say domain
and domain2
have the same schema and domain2
is empty, doing the following
所以我试了一下,是的,你可以0
用一条INSERT
语句得到一个返回值。如果您SELECT * FROM
的表没有行,INTO
另一个表可能会发生这种情况。例如,假设domain
和domain2
具有相同的架构并且domain2
为空,执行以下操作
Connection con = dataSource.getConnection();
PreparedStatement ps = con.prepareStatement("INSERT INTO domain SELECT * FROM domain2");
System.out.println(ps.executeUpdate());
prints 0
.
打印0
。
The only time I've ever used the return value of executeUpdate
is with a DELETE
statement on one row to make sure it existed before and was deleted. I don't think you should use it with INSERT
.
我唯一一次使用 的返回值executeUpdate
是DELETE
在一行上使用语句来确保它之前存在并被删除。我认为您不应该将它与INSERT
.
回答by Michael Edgar
For the example SQL you provided or for any SQL where a single row is to be inserted from parameters, the result would always be 1 if no SQLException occurs.
对于您提供的示例 SQL 或任何要从参数插入单行的 SQL,如果没有发生 SQLException,结果将始终为 1。
回答by Jerome
From the documentationof the executeUpdate()
method:
从该方法的文档中executeUpdate()
:
Returns: either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing
返回: (1) SQL 数据操作语言 (DML) 语句的行数或 (2) 0 不返回任何内容的 SQL 语句
0 seems like a perfectly natural result (i.e. not an error).
0 似乎是一个完全自然的结果(即不是错误)。
回答by Rodrigo
Read again:
再读一遍:
Returns: either (A) the row count for SQL Data Manipulation Language (DML) statements or (B) 0 for SQL statements that return nothing
返回: (A) SQL 数据操作语言 (DML) 语句的行数或 (B) 0 不返回任何内容的 SQL 语句