Saturday, October 25, 2008

executeBatch in JDBC

package jdbctest;
import java.sql.*;

public class TestConnection {
public TestConnection() {
try {

Driver d = (Driver)Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
DriverManager.registerDriver(d);
System.out.println("Oracle JDBC driver loaded.");

Connection conn = DriverManager.getConnection("jdbc:oracle:thin:cric/buzz@testsvr:1521:orcl");
Statement stmt = conn.createStatement();

stmt.addBatch("INSERT INTO TESTDTA.F0101 (ABAN8,ABALPH) values (223322,'Test')");
stmt.addBatch("INSERT INTO TESTDTA.F0101 (ABAN8,ABALPH) values (223323,'Test')");
stmt.addBatch("DELETE FROM TESTDTA.F0101 where ABAN8=223324");
int[] counts = stmt.executeBatch();
conn.close();

}
catch(Exception e) {
System.out.println("Exception"+ e);
}
}

public static void main(String[] args) {
TestConnection t = new TestConnection();

}
}

if one of the query in the batch fails, you will get BatchUpdateException.For example if you are trying to insert a duplicate record into F0101 table, you will get : Exceptionjava.sql.BatchUpdateException: error occurred during batching: ORA-00001: unique constraint (TESTDTA.F0101_PK) violated.

No comments: