2

I am using the following code to Insert data into a table.

test_conn.setAutoCommit(false);
stmt = test_conn.prepareStatement("INSERT INTO ...");

while(RSet.next()){
   for(int i = 1; i <= columnCount; i++){
       stmt.setString(i, RSet.getString(i));
   }
   stmt.addBatch();
}

stmt.executeBatch();
test_conn.commit();

other processing methods to occur only all the above rows are successfully inserted....

when I Insert into table using executeBatch(), if an SQL Exception or Error occurs in Inserting , is it possible to find Insertion of which Record has thrown the exception?

skaffman
  • 398,947
  • 96
  • 818
  • 769
Nagesh
  • 434
  • 1
  • 8
  • 26

1 Answers1

0

You have to try-catch the stmt.executeBatch() call and check for details in the exception. Batch execution will stop on first error that will occure.

Antoniossss
  • 31,590
  • 6
  • 57
  • 99
  • 2
    Yea. I know it will stop when batch fails. I want to know, how to get the Record which failed. – Nagesh Mar 18 '15 at 11:28
  • I think you cannot - the only thing is to hope that exceptin will have some guidence info from the RDBMS. Its like you would execute multiple SQLs separated with;. In case of error, it will not show you which statement failed. – Antoniossss Jul 28 '17 at 22:55
  • @codeFreak `stmt.executeBatch();` will return an integer array containing the insert status of each record. For i'th element, value `-3` indicates an `ERROR`, `>=0` indicates `OK` status. You can keep a separate array for maintaining the insert statements (`stmt.toString()`) and then compare with the result array to find the insert query which failed. – Arjun Sunil Kumar Dec 09 '20 at 17:26
  • @ArjunSK, could you give the source of this answer please? Does the error scenario when an element is -3 also applies when we run exexuteBatch for update queries? – Agent47 Dec 10 '20 at 06:41
  • @AkilaAmarasinghe int array values explanation https://stackoverflow.com/questions/48921660/what-does-return-value-3-indicate-when-sending-a-jdbc-bulk-insert-to-crate-io – Arjun Sunil Kumar Dec 10 '20 at 07:09