I am inserting data into table using executeBatch() method on PreparedStatement But When unique key constraint is violated then batch update exception is thrown. From BatchUpdateException when I call getUpdateCounts() method it returns empty array but actually 16 rows have been inserted into table.

Class.forName("oracle.jdbc.driver.OracleDriver");

Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@myhost:1521:orcl", "scott", "tiger");

try
{
  //Table PERSON has Primary Key on PNAME
  PreparedStatement prepStatement = connection.prepareStatement("INSERT INTO PERSON (PNAME, LOCATION, DOB, CONTACTNO) values (?, ?, ?, ?)");

  ResultSet employeeResultSet = getEmployeeResultSet( );

  //Only 17 rows are in employeeResultSet
  //Row number 16 and 17 has same PNAME which violates unique key constraint 
  while( employeeResultSet.next() )
  {
    prepStatement.setObject(1, employeeResultSet.getObject(1));
    prepStatement.setObject(2, employeeResultSet.getObject(2));
    prepStatement.setObject(3, employeeResultSet.getObject(3));
    prepStatement.setObject(4, employeeResultSet.getObject(4));

    prepStatement.addBatch();
  }
  prepStatement.executeBatch();
}
catch ( BatchUpdateException batchUpdateException ) 
{
  //updateCounts integer array is empty but actaully 15 rows have been inserted from batch
  int[] updateCounts = batchUpdateException.getUpdateCounts();
}

0 Answers