Deal with batch update exception and results
import java.sql.BatchUpdateException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class DemoBatchUpdateException {
public static Connection getMySQLConnection() throws Exception {
String driver = "org.gjt.mm.mysql.Driver";
String url = "jdbc:mysql://localhost/databaseName";
String username = "root";
String password = "root";
Class.forName(driver);
return DriverManager.getConnection(url, username, password);
}
public static void checkUpdateCounts(int[] updateCounts) {
for (int i = 0; i < updateCounts.length; i++) {
if (updateCounts[i] >= 0) {
// Successfully executed; the number represents number of affected rows
System.out.println("OK: updateCount=" + updateCounts[i]);
} else if (updateCounts[i] == Statement.SUCCESS_NO_INFO) {
// Successfully executed; number of affected rows not available
System.out.println("OK: updateCount=Statement.SUCCESS_NO_INFO");
} else if (updateCounts[i] == Statement.EXECUTE_FAILED) {
System.out.println("updateCount=Statement.EXECUTE_FAILED");
}
}
}
public static void main(String[] args)throws Exception {
Connection conn = getMySQLConnection();
Statement stmt = null;
try {
conn.setAutoCommit(false);
stmt = conn.createStatement();
stmt.addBatch("DELETE FROM animalsTable");
stmt.addBatch("INSERT INTO animalsTable(id, name) VALUES(1, 'A')");
stmt.addBatch("INSERT INTO animalsTable(id, name) VALUES(2, 'B')");
stmt.addBatch("INSERT INTO animalsTable(id, name) VALUES(3, 'C')");
int[] updateCounts = stmt.executeBatch();
checkUpdateCounts(updateCounts);
conn.commit();
} catch (BatchUpdateException e) {
int[] updateCounts = e.getUpdateCounts();
checkUpdateCounts(updateCounts);
try {
conn.rollback();
} catch (Exception e2) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
stmt.close();
conn.close();
}
}
}
Related examples in the same category