Batch Update Exception

From Java Example Source Code

Jump to: navigation, search

Contents

[edit] Overview - Batch Update Exception

This Java example program demonstrates Batch Update Exception.

[edit] Java Source Code

  • Package: example.batchupdate
  • File: DemoBatchUpdateException.java
package example.batchupdate;
 
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();
	}
    }
}

[edit] What Result You Can Get

Coming soon...

[edit] Required External Libraries and/or Files for this Java Example

Need nothing.

http://www.ase2009.com/ online casino 132 http://www.hellzyea.com/health health insurance 8DDD http://www.yourautoinsurancesite.com/ auto insurance quotes 135811 http://www.makemeasammich.com/ auto insurance mcnxu

[edit] Question & Answer

Any question?

Click edit and post your question or answer here.


Personal tools