简体   繁体   中英

Can PreparedStatement.executeUpdate() ever return 0 on INSERT?

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?

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.

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

Connection con = dataSource.getConnection();
PreparedStatement ps = con.prepareStatement("INSERT INTO domain SELECT * FROM domain2");
System.out.println(ps.executeUpdate());

prints 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 .

From the documentation of the executeUpdate() method:

Returns: either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing

0 seems like a perfectly natural result (ie not an error).

对于您提供的示例 SQL 或任何要从参数插入单行的 SQL,如果没有发生 SQLException,结果将始终为 1。

Read again:

Returns: either (A) the row count for SQL Data Manipulation Language (DML) statements or (B) 0 for SQL statements that return nothing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM