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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With