I have a doubt related to Prepared Statement in Java as I don't know much about it.
I have a use case in which I have to use PreparedStatement. But I am just thinking before writing code that:
while(...)
{
if(...)
{
preparedStatement.setString(1, fname);
preparedStatement.setString(2, lname);
...
preparedStatement.addBatch();
}
}
preparedStatement.executeBatch();
Lets Consider the above code. There is a while loop which will do some stuff and then check some condition and then add the batch in prepared statement.
1) So, my question is that suppose none of the batch is added in prepared statement and still I say executeBatch
. Does it give me exception or will execute fine?
2) Is there any method to check the batch in preparedstatement before execute?
Thanks.
It should just work fine and return an empty array. The only way to know if there are batches currently added, AFAIK, is to keep track of them yourself.
If on the other hand you only want to know how many statements you actually executed, then you can use the array of update counts that was returned to check how many queries were run, and the individual values therein to see for each of them if they were successful. See the documentation of executeBatch()
for more details.
You need not worry about handling this case. Once you become familiar with writing API's you should expect the standard that the javadoc will give you a throws clause:
Throws:SQLException - if a database access error occurs, this method
is called on a closed Statement or the driver does not support batch
statements. Throws BatchUpdateException (a subclass of SQLException)
if one of the commands sent to the database fails to execute properly
or attempts to return a result set.SQLTimeoutException - when the
driver has determined that the timeout value that was specified by the
setQueryTimeout method has been exceeded and has at least attempted to
cancel the currently running Statement
Moreover, if you are skeptical, consider the return type, int[] java.sql.Statement.executeBatch()
Expect object to be null in an API, and standard primitives/base types to return empty or initialized values
As WDS stated, it should return an empty int array.
if(preparedstatement.executeBatch().length == 0){
//do somethimg
}
Basically tests if the batch has no statements ;-)