/** * static method testing jdbc framework with multiple updates and intentional sql exceptions that * are trapped in appropriate exception handling blocks */ public static void testMultipleUpdatesAndTransWithException() { ConnectionPool conPool = getConnectionPool(); SQLExecutor sqlExec = new SQLExecutor(conPool); try { sqlExec.setAutoCommit(false); sqlExec.addParam(new Integer(7)); sqlExec.runQuery("UPDATE JDBC_TEST SET CODE = 'Z' WHERE TEST_ID = ?"); sqlExec.addParam(new Integer(6)); // integrity constraint violation sqlExec.runQuery("UPDATE JDBC_TEST SET TEST_ID = NULL WHERE TEST_ID = ?"); sqlExec.commitTrans(); System.out.println("transaction committed"); } catch (DatabaseException e) { System.out.println("Error code=" + e.getSQLErrorCode() + ", SQLState=" + e.getSQLState()); if (e.isDataIntegrityViolation()) System.out.println("data integrity violation"); else if (e.isBadSQLGrammar()) System.out.println("bad SQL grammar"); else if (e.isNonExistentTableOrViewOrCol()) System.out.println("Non existent table or view"); System.out.println(e.getMessage()); sqlExec.rollbackTrans(); System.out.println("transaction rolled back"); } finally { sqlExec.closeConnection(); } }
private synchronized void init() throws DatabaseException { status = PwmService.STATUS.OPENING; LOGGER.debug("opening connection to database " + this.dbConfiguration.getConnectionString()); connection = openDB(dbConfiguration); for (final DatabaseTable table : DatabaseTable.values()) { initTable(connection, table, dbConfiguration); } status = PwmService.STATUS.OPEN; try { put( DatabaseTable.PWM_META, KEY_ENGINE_START_PREFIX + instanceID, PwmConstants.DEFAULT_DATETIME_FORMAT.format(new java.util.Date())); } catch (DatabaseException e) { final String errorMsg = "error writing engine start time value: " + e.getMessage(); throw new DatabaseException(new ErrorInformation(PwmError.ERROR_DB_UNAVAILABLE, errorMsg)); } }
/** * static method testing jdbc framework with a select for update statement (that locks a record) * and an update statement that generates a deadlock. */ public static void testDeadlockException() { ConnectionPool conPool = getConnectionPool(); SQLExecutor sqlExec1 = new SQLExecutor(conPool); try { // lock record with a select for update statement sqlExec1.setAutoCommit(false); sqlExec1.addParam(new Integer(2)); sqlExec1.runQuery("SELECT CODE FROM JDBC_TEST WHERE TEST_ID = ? FOR UPDATE"); System.out.println("Attempting to update a record locked by another connection..."); SQLExecutor sqlExec2 = new SQLExecutor(getConnectionPool()); sqlExec2.setTimeoutInSec(5); // timeout if deadlocked sqlExec2.addParam(new Integer(2)); sqlExec2.runQueryCloseCon("UPDATE JDBC_TEST SET CODE = 'X' WHERE TEST_ID = ?"); } catch (DatabaseException e) { System.out.println("Error code=" + e.getSQLErrorCode() + ", " + e.getMessage()); if (e.isRowlockOrTimedOut()) System.out.println("Rowlock exception!"); } finally { conPool.closeAllConnections(); } }