BatchUpdateException | Java

 

Descripción

Sintaxis

public class BatchUpdateException extends SQLException

Constructores

Métodos

Ejemplo

public class ErrorBatchUpdate {
  public static void main(String[] args) throws SQLException {

    Connection con = null;
    String sURL = "jdbc:mysql://localhost:3306/lineadecodigo";

    try {
      con = DriverManager.getConnection(sURL,"root","");
      con.setAutoCommit(false);
	      
      PreparedStatement stmt = con.prepareStatement("CREATE TABLE temporal (numero TINYINT(1) NOT NULL)");  
      stmt.execute(); 
      stmt.close();
      
      stmt = con.prepareStatement("CREATE UNIQUE INDEX indicenumero ON temporal(numero)");  
      stmt.execute(); 
      stmt.close();	     

      int[] valores = {1,2,2,3,1,4,1,2};	      
	      
      try {       
        PreparedStatement carga = con.prepareStatement("INSERT INTO temporal VALUES (?)");	    	 
   	  
        for (int x=0;x<valores.length;x++) {
          carga.setInt(1, valores[x]);
          carga.addBatch();
        }
        carga.executeBatch();

      } catch (BatchUpdateException bue) {
        int[] errores = bue.getUpdateCounts();
        System.out.println("--Errores en el Batch--\n");
   	  
        for (int x=0;x<errores.length;x++) {
          if (errores[x] < 0) 
            System.out.print("Error insertando el valor " + valores[x] + " de la posición " + x + "\n");
        }		    	  	    	 	    	  
      }

      con.commit();
 
      stmt = con.prepareStatement("DROP TABLE temporal");  
      stmt.execute(); 
      stmt.close();
   
    } catch (SQLException sqle) { 
      System.out.println(sqle.getMessage());
      con.rollback();	      
    } finally {
      if (con!=null) con.close();    	      
    } 
   }
 }

Líneas de Código

    Manual Java

    Aprende más sobre Java consultando online o descargando nuestro manual.

    Test Java

    ¿Te atreves a probar tus habilidades y conocimiento en Java con nuestro test?

    Vídeos Java

    Disfruta también de nuestros artículos sobre Java en formato vídeo. Aprovecha y suscribete a nuestro canal.