Krishita Chawla February 2016

Discovering which records of a batch update failed

i am making a batch update of 1000 records in java using jdbc. Out of them 800 records were updated sucessfully and 200 falied . so i want to check from batch update query that which all 200 records were failed to b updated and i will insert them in database using batch insert . how can i achieve that ?

Answers


andrucz February 2016

executeBath() method from Statement returns an array of integers (one integer per command that was executed). Each integer represents update count. If 1 or greater, update was done successfully; if 0, no record was updated with its respective command.

Example:

List<YourClass> objectsToUpdate = getObjectsToUpdate();

for (YourClass object : objectsToUpdate) {
    String updateCommand = generateUpdateCommand(object);
    statement.addBatch(updateCommand);
}
int[] results = statement.executeBatch();

List<YourClass> notUpdated = new ArrayList<YourObject>();

for (int i = 0; i < results.length; i++) {
    if (results[i] == 0) {
        notUpdated.add(objectsToUpdate.get(i));
    }
}

That was just to demonstrate the algorithm. Consider using PreparedStatement instead of Statement.


dsp_user February 2016

For completeness, it's also important to say that when using batch updates, a JDBC driver may also return (as part of the integer array) Statement.SUCCESS_NO_INFO (when no information on updated rows is available) or Statement.EXECUTE_FAILED (when an exception occurs)

Some JDBC drivers may even stop executing further statements (updates) in case of an exception.

Post Status

Asked in February 2016
Viewed 2,692 times
Voted 5
Answered 2 times

Search




Leave an answer