List of usage examples for java.sql BatchUpdateException getMessage
public String getMessage()
From source file:TestBatchUpdate.java
public static void main(String args[]) { Connection conn = null;//from w ww. j a va 2 s. c o m Statement stmt = null; ResultSet rs = null; try { conn = getConnection(); stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); conn.setAutoCommit(false); stmt.addBatch("INSERT INTO batch_table(id, name) VALUES('11', 'A')"); stmt.addBatch("INSERT INTO batch_table(id, name) VALUES('22', 'B')"); stmt.addBatch("INSERT INTO batch_table(id, name) VALUES('33', 'C')"); int[] updateCounts = stmt.executeBatch(); conn.commit(); rs = stmt.executeQuery("SELECT * FROM batch_table"); while (rs.next()) { String id = rs.getString("id"); String name = rs.getString("name"); System.out.println("id=" + id + " name=" + name); } } catch (BatchUpdateException b) { System.err.println("SQLException: " + b.getMessage()); System.err.println("SQLState: " + b.getSQLState()); System.err.println("Message: " + b.getMessage()); System.err.println("Vendor error code: " + b.getErrorCode()); System.err.print("Update counts: "); int[] updateCounts = b.getUpdateCounts(); for (int i = 0; i < updateCounts.length; i++) { System.err.print(updateCounts[i] + " "); } } catch (SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); System.err.println("SQLState: " + ex.getSQLState()); System.err.println("Message: " + ex.getMessage()); System.err.println("Vendor error code: " + ex.getErrorCode()); } catch (Exception e) { System.err.println("Exception: " + e.getMessage()); } finally { try { rs.close(); stmt.close(); conn.close(); } catch (Exception ignore) { } } }
From source file:BatchUpdate.java
public static void main(String args[]) { String url = "jdbc:mySubprotocol:myDataSource"; Connection con;/* ww w . j a va2 s . c o m*/ Statement stmt; try { Class.forName("myDriver.ClassName"); } catch (java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); } try { con = DriverManager.getConnection(url, "myLogin", "myPassword"); stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); con.setAutoCommit(false); stmt.addBatch("INSERT INTO COFFEES " + "VALUES('Amaretto', 49, 9.99, 0, 0)"); stmt.addBatch("INSERT INTO COFFEES " + "VALUES('Hazelnut', 49, 9.99, 0, 0)"); stmt.addBatch("INSERT INTO COFFEES " + "VALUES('Amaretto_decaf', 49, 10.99, 0, 0)"); stmt.addBatch("INSERT INTO COFFEES " + "VALUES('Hazelnut_decaf', 49, 10.99, 0, 0)"); int[] updateCounts = stmt.executeBatch(); ResultSet uprs = stmt.executeQuery("SELECT * FROM COFFEES"); System.out.println("Table COFFEES after insertion:"); while (uprs.next()) { String name = uprs.getString("COF_NAME"); int id = uprs.getInt("SUP_ID"); float price = uprs.getFloat("PRICE"); int sales = uprs.getInt("SALES"); int total = uprs.getInt("TOTAL"); System.out.print(name + " " + id + " " + price); System.out.println(" " + sales + " " + total); } uprs.close(); stmt.close(); con.close(); } catch (BatchUpdateException b) { System.err.println("SQLException: " + b.getMessage()); System.err.println("SQLState: " + b.getSQLState()); System.err.println("Message: " + b.getMessage()); System.err.println("Vendor: " + b.getErrorCode()); System.err.print("Update counts: "); int[] updateCounts = b.getUpdateCounts(); for (int i = 0; i < updateCounts.length; i++) { System.err.print(updateCounts[i] + " "); } } catch (SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); System.err.println("SQLState: " + ex.getSQLState()); System.err.println("Message: " + ex.getMessage()); System.err.println("Vendor: " + ex.getErrorCode()); } }
From source file:CreateRef.java
public static void main(String args[]) { String url = "jdbc:mySubprotocol:myDataSource"; Connection con;/*w w w . j av a2 s. c om*/ Statement stmt; try { Class.forName("myDriver.ClassName"); } catch (java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); } try { String createManagers = "CREATE TABLE MANAGERS OF MANAGER " + "(OID REF(MANAGER) VALUES ARE SYSTEM GENERATED)"; String insertManager1 = "INSERT INTO MANAGERS " + "(MGR_ID, LAST_NAME, FIRST_NAME, PHONE) VALUES " + "(000001, 'MONTOYA', 'ALFREDO', '8317225600')"; String insertManager2 = "INSERT INTO MANAGERS " + "(MGR_ID, LAST_NAME, FIRST_NAME, PHONE) VALUES " + "(000002, 'HASKINS', 'MARGARET', '4084355600')"; String insertManager3 = "INSERT INTO MANAGERS " + "(MGR_ID, LAST_NAME, FIRST_NAME, PHONE) VALUES " + "(000003, 'CHEN', 'HELEN', '4153785600')"; con = DriverManager.getConnection(url, "myLogin", "myPassword"); stmt = con.createStatement(); stmt.executeUpdate(createManagers); con.setAutoCommit(false); stmt.addBatch(insertManager1); stmt.addBatch(insertManager2); stmt.addBatch(insertManager3); int[] updateCounts = stmt.executeBatch(); con.commit(); System.out.println("Update count for: "); for (int i = 0; i < updateCounts.length; i++) { System.out.print(" command " + (i + 1) + " = "); System.out.println(updateCounts[i]); } stmt.close(); con.close(); } catch (BatchUpdateException b) { System.err.println("-----BatchUpdateException-----"); System.err.println("Message: " + b.getMessage()); System.err.println("SQLState: " + b.getSQLState()); System.err.println("Vendor: " + b.getErrorCode()); System.err.print("Update counts for successful commands: "); int[] rowsUpdated = b.getUpdateCounts(); for (int i = 0; i < rowsUpdated.length; i++) { System.err.print(rowsUpdated[i] + " "); } System.err.println(""); } catch (SQLException ex) { System.err.println("------SQLException------"); System.err.println("Error message: " + ex.getMessage()); System.err.println("SQLState: " + ex.getSQLState()); System.err.println("Vendor: " + ex.getErrorCode()); } }
From source file:BatchUpdate.java
public static void main(String args[]) throws SQLException { ResultSet rs = null;//from w ww .j a v a 2 s . c o m PreparedStatement ps = null; String url = "jdbc:mySubprotocol:myDataSource"; Connection con; Statement stmt; try { Class.forName("myDriver.ClassName"); } catch (java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); } try { con = DriverManager.getConnection(url, "myLogin", "myPassword"); con.setAutoCommit(false); stmt = con.createStatement(); stmt.addBatch("INSERT INTO COFFEES " + "VALUES('Amaretto', 49, 9.99, 0, 0)"); stmt.addBatch("INSERT INTO COFFEES " + "VALUES('Hazelnut', 49, 9.99, 0, 0)"); stmt.addBatch("INSERT INTO COFFEES " + "VALUES('Amaretto_decaf', 49, 10.99, 0, 0)"); stmt.addBatch("INSERT INTO COFFEES " + "VALUES('Hazelnut_decaf', 49, 10.99, 0, 0)"); int[] updateCounts = stmt.executeBatch(); con.commit(); con.setAutoCommit(true); ResultSet uprs = stmt.executeQuery("SELECT * FROM COFFEES"); System.out.println("Table COFFEES after insertion:"); while (uprs.next()) { String name = uprs.getString("COF_NAME"); int id = uprs.getInt("SUP_ID"); float price = uprs.getFloat("PRICE"); int sales = uprs.getInt("SALES"); int total = uprs.getInt("TOTAL"); System.out.print(name + " " + id + " " + price); System.out.println(" " + sales + " " + total); } uprs.close(); stmt.close(); con.close(); } catch (BatchUpdateException b) { System.err.println("-----BatchUpdateException-----"); System.err.println("SQLState: " + b.getSQLState()); System.err.println("Message: " + b.getMessage()); System.err.println("Vendor: " + b.getErrorCode()); System.err.print("Update counts: "); int[] updateCounts = b.getUpdateCounts(); for (int i = 0; i < updateCounts.length; i++) { System.err.print(updateCounts[i] + " "); } System.err.println(""); } catch (SQLException ex) { System.err.println("-----SQLException-----"); System.err.println("SQLState: " + ex.getSQLState()); System.err.println("Message: " + ex.getMessage()); System.err.println("Vendor: " + ex.getErrorCode()); } }
From source file:InsertStores.java
public static void main(String args[]) { String url = "jdbc:mySubprotocol:myDataSource"; Connection con;/*w w w .j a v a 2 s. c o m*/ Statement stmt; try { Class.forName("myDriver.ClassName"); } catch (java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); } try { con = DriverManager.getConnection(url, "myLogin", "myPassword"); stmt = con.createStatement(); con.setAutoCommit(false); String insertStore1 = "INSERT INTO STORES VALUES (" + "100001, " + "ADDRESS(888, 'Main_Street', 'Rancho_Alegre', " + "'CA', '94049'), " + "COF_ARRAY('Colombian', 'French_Roast', 'Espresso', " + "'Colombian_Decaf', 'French_Roast_Decaf'), " + "(SELECT OID FROM MANAGERS WHERE MGR_ID = 000001))"; stmt.addBatch(insertStore1); String insertStore2 = "INSERT INTO STORES VALUES (" + "100002, " + "ADDRESS(1560, 'Alder', 'Ochos_Pinos', " + "'CA', '94049'), " + "COF_ARRAY('Colombian', 'French_Roast', 'Espresso', " + "'Colombian_Decaf', 'French_Roast_Decaf', " + "'Kona', 'Kona_Decaf'), " + "(SELECT OID FROM MANAGERS WHERE MGR_ID = 000001))"; stmt.addBatch(insertStore2); String insertStore3 = "INSERT INTO STORES VALUES (" + "100003, " + "ADDRESS(4344, 'First_Street', 'Verona', " + "'CA', '94545'), " + "COF_ARRAY('Colombian', 'French_Roast', 'Espresso', " + "'Colombian_Decaf', 'French_Roast_Decaf', " + "'Kona', 'Kona_Decaf'), " + "(SELECT OID FROM MANAGERS WHERE MGR_ID = 000002))"; stmt.addBatch(insertStore3); String insertStore4 = "INSERT INTO STORES VALUES (" + "100004, " + "ADDRESS(321, 'Sandy_Way', 'La_Playa', " + "'CA', '94544'), " + "COF_ARRAY('Colombian', 'French_Roast', 'Espresso', " + "'Colombian_Decaf', 'French_Roast_Decaf', " + "'Kona', 'Kona_Decaf'), " + "(SELECT OID FROM MANAGERS WHERE MGR_ID = 000002))"; stmt.addBatch(insertStore4); String insertStore5 = "INSERT INTO STORES VALUES (" + "100005, " + "ADDRESS(1000, 'Clover_Road', 'Happyville', " + "'CA', '90566'), " + "COF_ARRAY('Colombian', 'French_Roast', 'Espresso', " + "'Colombian_Decaf', 'French_Roast_Decaf'), " + "(SELECT OID FROM MANAGERS WHERE MGR_ID = 000003))"; stmt.addBatch(insertStore5); int[] updateCounts = stmt.executeBatch(); ResultSet rs = stmt.executeQuery("SELECT * FROM STORES"); System.out.println("Table STORES after insertion:"); System.out.println("STORE_NO LOCATION COF_TYPE MGR"); while (rs.next()) { int storeNo = rs.getInt("STORE_NO"); Struct location = (Struct) rs.getObject("LOCATION"); Object[] locAttrs = location.getAttributes(); Array coffeeTypes = rs.getArray("COF_TYPE"); String[] cofTypes = (String[]) coffeeTypes.getArray(); Ref managerRef = rs.getRef("MGR"); PreparedStatement pstmt = con.prepareStatement("SELECT MANAGER FROM MANAGERS WHERE OID = ?"); pstmt.setRef(1, managerRef); ResultSet rs2 = pstmt.executeQuery(); rs2.next(); Struct manager = (Struct) rs2.getObject("MANAGER"); Object[] manAttrs = manager.getAttributes(); System.out.print(storeNo + " "); System.out.print(locAttrs[0] + " " + locAttrs[1] + " " + locAttrs[2] + ", " + locAttrs[3] + " " + locAttrs[4] + " "); for (int i = 0; i < cofTypes.length; i++) System.out.print(cofTypes[i] + " "); System.out.println(manAttrs[1] + ", " + manAttrs[2]); rs2.close(); pstmt.close(); } rs.close(); stmt.close(); con.close(); } catch (BatchUpdateException b) { System.err.println("-----BatchUpdateException-----"); System.err.println("SQLState: " + b.getSQLState()); System.err.println("Message: " + b.getMessage()); System.err.println("Vendor: " + b.getErrorCode()); System.err.print("Update counts: "); int[] updateCounts = b.getUpdateCounts(); for (int i = 0; i < updateCounts.length; i++) { System.err.print(updateCounts[i] + " "); } System.err.println(""); } catch (SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); System.err.println("SQLState: " + ex.getSQLState()); System.err.println("Message: " + ex.getMessage()); System.err.println("Vendor: " + ex.getErrorCode()); } }
From source file:com.oracle.tutorial.jdbc.JDBCTutorialUtilities.java
public static void printBatchUpdateException(BatchUpdateException b) { System.err.println("----BatchUpdateException----"); System.err.println("SQLState: " + b.getSQLState()); System.err.println("Message: " + b.getMessage()); System.err.println("Vendor: " + b.getErrorCode()); System.err.print("Update counts: "); int[] updateCounts = b.getUpdateCounts(); for (int i = 0; i < updateCounts.length; i++) { System.err.print(updateCounts[i] + " "); }/*from w ww . j a v a2s . co m*/ }
From source file:com.dattack.dbcopy.engine.InsertOperationContext.java
private int executeBatch() throws SQLException { int insertedRows = 0; try {/* www . j av a 2s .c om*/ final int[] batchResult = getPreparedStatement().executeBatch(); for (int i = 0; i < batchResult.length; i++) { if (batchResult[i] > 0) { insertedRows += batchResult[i]; } else if (batchResult[i] == Statement.SUCCESS_NO_INFO) { insertedRows++; } } } catch (final BatchUpdateException e) { LOGGER.warn("Batch operation failed: {} (SQLSTATE: {}, Error code: {}, Executed statements: {})", e.getMessage(), e.getSQLState(), e.getErrorCode(), e.getUpdateCounts().length); } getConnection().commit(); return insertedRows; }
From source file:com.wavemaker.runtime.data.spring.SpringDataServiceManager.java
private Object runInTx(Task task, Object... input) { HibernateCallback action = new RunInHibernate(task, input); TransactionTemplate txTemplate = new TransactionTemplate(this.txMgr); boolean rollbackOnly = task instanceof DefaultRollback && !isTxRunning(); RunInTx tx = new RunInTx(action, rollbackOnly); if (txLogger.isInfoEnabled()) { if (isTxRunning()) { txLogger.info("tx is running executing \"" + task.getName() + "\" in current tx"); } else {/*from w ww .j av a 2 s . c o m*/ txLogger.info("no tx running, wrapping execution of \"" + task.getName() + "\" in tx"); if (rollbackOnly) { txLogger.info("rollback enabled for \"" + task.getName() + "\""); } } } Object rtn = null; try { rtn = txTemplate.execute(tx); } catch (Throwable ex) { //The following logic intends to display a sensible message for the user when a column contains a value whose length //exceeds the maximum length allowed in the database. The logic has been tested on MySQL, Postgres, Oracle and //SQLServer so far. if (ex.getCause() instanceof java.sql.BatchUpdateException) { //Oracle String msg = ((java.sql.BatchUpdateException) ex.getCause()).getNextException().getMessage(); if (msg != null) { ex.printStackTrace(); throw new WMRuntimeException(msg); } } else if (ex.getCause().getCause() instanceof java.sql.BatchUpdateException) { //Postgres java.sql.BatchUpdateException e = (java.sql.BatchUpdateException) ex.getCause().getCause(); if (e != null && e.getMessage() != null) { ex.printStackTrace(); throw new WMRuntimeException(e.getNextException().getMessage()); } } else if (ex.getCause().getCause() != null) { //MySQL, SQLServer String msg = ex.getCause().getCause().getMessage(); if (msg != null) { ex.printStackTrace(); throw new WMRuntimeException(msg); } } else { throw new WMRuntimeException(ex); } } if (txLogger.isInfoEnabled()) { if (isTxRunning()) { txLogger.info("tx is running after execution of \"" + task.getName() + "\""); } else { txLogger.info("tx is not running after execution of \"" + task.getName() + "\""); } } return rtn; }
From source file:ConsumerServer.java
public void processMessages() { // for this exercise start from offset 0 // produce batches of n size for jdbc and insert // for this table // char(10), char(20), long String sqlInsert = "INSERT INTO kblog.BLOGDATA VALUES (?,?,?,?,?)"; String sqlUpsert = "UPSERT INTO kblog.BLOGDATA VALUES (?,?,?,?,?)"; final String UDFCALL = " select * from udf(kblog.kaf3('nap007:9092'," + " 'gid'," + " 'blogit'," + " 0," + " 'null'," + " 'C10C20IC55C55'," + " '|'," + " -1," + " 1000 ))"; final String SQLUPSERT = "upsert using load into kblog.blogdata "; final String SQLINSERT = "insert into kblog.blogdata "; final String SQLUPSERT2 = "upsert into kblog.blogdata "; try {/*w w w . jav a 2s . co m*/ if (t2Connect) { // T2 Class.forName("org.apache.trafodion.jdbc.t2.T2Driver"); conn = DriverManager.getConnection("jdbc:t2jdbc:"); } else { // T4 Class.forName("org.trafodion.jdbc.t4.T4Driver"); conn = DriverManager.getConnection("jdbc:t4jdbc://nap007:23400/:", "trafodion", "passw"); } conn.setAutoCommit(autoCommit); } catch (SQLException sx) { System.out.println("SQL error: " + sx.getMessage()); System.exit(1); } catch (ClassNotFoundException cx) { System.out.println("Driver class not found: " + cx.getMessage()); System.exit(2); } // message processing loop String[] msgFields; long numRows = 0; long totalRows = 0; int[] batchResult; if (udfMode == 0 && insMode == 0) { // missing cmd line setting System.out.println("*** Neither UDF nor INSERT mode specified - aborting ***"); System.exit(2); } try { if (udfMode > 0) { long diff = 0; long startTime = System.currentTimeMillis(); switch (udfMode) { case 1: // upsert using load pStmt = conn.prepareStatement(SQLUPSERT + UDFCALL); totalRows = pStmt.executeUpdate(); diff = (System.currentTimeMillis() - startTime); System.out.println("Upsert loaded row count: " + totalRows + " in " + diff + " ms"); break; case 2: // insert pStmt = conn.prepareStatement(SQLINSERT + UDFCALL); totalRows = pStmt.executeUpdate(); if (!autoCommit) { conn.commit(); diff = (System.currentTimeMillis() - startTime); System.out .println("Insert row count (autocommit off): " + totalRows + " in " + diff + " ms"); } else { diff = (System.currentTimeMillis() - startTime); System.out .println("Insert row count (autocommit on): " + totalRows + " in " + diff + " ms"); } break; case 3: // upsert pStmt = conn.prepareStatement(SQLUPSERT2 + UDFCALL); totalRows = pStmt.executeUpdate(); if (!autoCommit) { conn.commit(); diff = (System.currentTimeMillis() - startTime); System.out .println("Upsert row count (autocommit off): " + totalRows + " in " + diff + " ms"); } else { diff = (System.currentTimeMillis() - startTime); System.out .println("Upsert row count (autocommit on): " + totalRows + " in " + diff + " ms"); } break; default: // illegal value System.out.println("*** Only udf values 1,2,3 allowed; found: " + udfMode); System.exit(2); } // switch } // udfMode else { // iterative insert/upsert switch (insMode) { case 1: // insert pStmt = conn.prepareStatement(sqlInsert); break; case 2: //upsert pStmt = conn.prepareStatement(sqlUpsert); break; default: // illegal System.out.println("*** Only insert values 1,2 allowed; found: " + insMode); System.exit(2); } // switch kafka.subscribe(Arrays.asList(topic)); // priming poll kafka.poll(100); // always start from beginning kafka.seekToBeginning(Arrays.asList(new TopicPartition(topic, 0))); // enable autocommit and singleton inserts for comparative timings long startTime = System.currentTimeMillis(); while (true) { // note that we don't commitSync to kafka - tho we should ConsumerRecords<String, String> records = kafka.poll(streamTO); if (records.isEmpty()) break; // timed out for (ConsumerRecord<String, String> msg : records) { msgFields = msg.value().split("\\" + Character.toString(delimiter)); // position info for this message long offset = msg.offset(); int partition = msg.partition(); String topic = msg.topic(); pStmt.setString(1, msgFields[0]); pStmt.setString(2, msgFields[1]); pStmt.setLong(3, Long.parseLong(msgFields[2])); pStmt.setString(4, msgFields[3]); pStmt.setString(5, msgFields[4]); numRows++; totalRows++; if (autoCommit) { // single ins/up sert pStmt.executeUpdate(); } else { pStmt.addBatch(); if ((numRows % commitCount) == 0) { numRows = 0; batchResult = pStmt.executeBatch(); conn.commit(); } } } // for each msg } // while true // get here when poll returns no records if (numRows > 0 && !autoCommit) { // remaining rows batchResult = pStmt.executeBatch(); conn.commit(); } long diff = (System.currentTimeMillis() - startTime); if (autoCommit) System.out.println("Total rows: " + totalRows + " in " + diff + " ms"); else System.out.println( "Total rows: " + totalRows + " in " + diff + " ms; batch size = " + commitCount); kafka.close(); } // else } // try catch (ConsumerTimeoutException to) { System.out.println("consumer time out; " + to.getMessage()); System.exit(1); } catch (BatchUpdateException bx) { int[] insertCounts = bx.getUpdateCounts(); int count = 1; for (int i : insertCounts) { if (i == Statement.EXECUTE_FAILED) System.out.println("Error on request #" + count + ": Execute failed"); else count++; } System.out.println(bx.getMessage()); System.exit(1); } catch (SQLException sx) { System.out.println("SQL error: " + sx.getMessage()); System.exit(1); } }
From source file:jade.domain.DFDBKB.java
/** * Builds an error message for a <code>BatchUpdateException</code> *//*from www . j a v a 2s . c o m*/ private String getBatchUpdateErroMsg(BatchUpdateException e) { StringBuffer msg = new StringBuffer("SQLException: " + e.getMessage() + "\n"); msg.append("SQLState: " + e.getSQLState() + "\n"); msg.append("Message: " + e.getMessage() + "\n"); msg.append("Vendor: " + e.getErrorCode() + "\n"); msg.append("Update counts: "); int[] updateCounts = e.getUpdateCounts(); for (int i = 0; i < updateCounts.length; i++) { msg.append(updateCounts[i] + " "); } return msg.toString(); }