List of usage examples for java.sql Connection getAutoCommit
boolean getAutoCommit() throws SQLException;
Connection
object. From source file:org.etudes.jforum.util.search.quartz.QuartzSearchIndexerJob.java
/** * @see org.quartz.Job#execute(org.quartz.JobExecutionContext) *//*from w w w . ja v a 2 s. c o m*/ public void execute(JobExecutionContext context) throws JobExecutionException { if ("1".equals(cache.get(FQN, INDEXING))) { logger.info("Indexing is already running. Going home..."); return; } Properties p = this.loadConfig(); if (p == null) { return; } Connection connStatus = null; // if status is started return from processing the indexing. Update database the status of the indexing to started try { if (logger.isDebugEnabled()) logger.debug("Getting the index status"); connStatus = DBConnection.getImplementation().getConnection(); boolean statusStarted = DataAccessDriver.getInstance().newScheduledSearchIndexerDAO() .indexingStatus(connStatus); if (logger.isDebugEnabled()) logger.debug("The index status is " + statusStarted); if (statusStarted) { if (connStatus != null) { DBConnection.getImplementation().releaseConnection(connStatus); } return; } else { DataAccessDriver.getInstance().newScheduledSearchIndexerDAO().addStatus(connStatus); } } catch (Exception e1) { if (logger.isErrorEnabled()) logger.error("Error while getting the status." + e1, new Throwable(e1)); if (connStatus != null) { DBConnection.getImplementation().releaseConnection(connStatus); } return; } int step = Integer.parseInt(p.getProperty(ConfigKeys.QUARTZ_CONTEXT + ConfigKeys.SEARCH_INDEXER_STEP)); Connection conn = null; boolean autoCommit = false; try { conn = DBConnection.getImplementation().getConnection(); autoCommit = conn.getAutoCommit(); conn.setAutoCommit(true); cache.add(FQN, INDEXING, "1"); ScheduledSearchIndexerDAO dao = DataAccessDriver.getInstance().newScheduledSearchIndexerDAO(); dao.index(step, conn); } catch (Exception e) { logger.error("Error while trying to index messagez. Cannot proceed. " + e); e.printStackTrace(); } finally { cache.remove(FQN, INDEXING); if (conn != null) { try { conn.setAutoCommit(autoCommit); } catch (Exception e) { } DBConnection.getImplementation().releaseConnection(conn); } // status related try { DataAccessDriver.getInstance().newScheduledSearchIndexerDAO().deleteStatus(connStatus); } catch (Exception e) { if (logger.isErrorEnabled()) logger.error("Error while deleting the status." + e, new Throwable(e)); } finally { if (connStatus != null) { DBConnection.getImplementation().releaseConnection(connStatus); } } } }
From source file:org.rimudb.DBCPPoolTests.java
@Test public void testConnectionAttributes() throws Exception { // Connect to the database CompoundDatabase cdb = new CompoundDatabase("/testconfig/pooltests-dbcp-2-jdbcconfig.xml", true); cdb.connect("dbid-1"); Database db = cdb.getDatabase("dbid-1"); Connection conn = db.getDatabaseConnection(); assertEquals("Wrong transaction isolation", Connection.TRANSACTION_READ_COMMITTED, conn.getTransactionIsolation()); assertEquals("Wrong auto commit", false, conn.getAutoCommit()); db.disconnect();/* w w w . j a v a2s .c om*/ cdb.connect("dbid-2"); db = cdb.getDatabase("dbid-2"); conn = db.getDatabaseConnection(); assertEquals("Wrong transaction isolation", Connection.TRANSACTION_READ_UNCOMMITTED, conn.getTransactionIsolation()); assertEquals("Wrong auto commit", true, conn.getAutoCommit()); db.disconnect(); cdb.connect("dbid-3"); db = cdb.getDatabase("dbid-3"); conn = db.getDatabaseConnection(); assertEquals("Wrong transaction isolation", Connection.TRANSACTION_REPEATABLE_READ, conn.getTransactionIsolation()); assertEquals("Wrong auto commit", false, conn.getAutoCommit()); db.disconnect(); cdb.connect("dbid-4"); db = cdb.getDatabase("dbid-4"); conn = db.getDatabaseConnection(); assertEquals("Wrong transaction isolation", Connection.TRANSACTION_SERIALIZABLE, conn.getTransactionIsolation()); assertEquals("Wrong auto commit", true, conn.getAutoCommit()); db.disconnect(); cdb.disconnectAllNoException(); }
From source file:com.concursive.connect.web.modules.profile.dao.ProjectCategoryLogoFile.java
public boolean insert(Connection db) throws SQLException { boolean result = false; // The required linkModuleId linkModuleId = Constants.PROJECT_CATEGORY_FILES; // Determine if the database is in auto-commit mode boolean doCommit = false; try {//from ww w.j a va 2 s . c o m if (doCommit = db.getAutoCommit()) { db.setAutoCommit(false); } // Insert the record result = super.insert(db); // Update the referenced pointer if (result) { int i = 0; PreparedStatement pst = db.prepareStatement( "UPDATE lookup_project_category " + "SET logo_id = ? " + "WHERE code = ? "); pst.setInt(++i, id); pst.setInt(++i, linkItemId); int count = pst.executeUpdate(); result = (count == 1); } if (doCommit) { db.commit(); } } catch (Exception e) { if (doCommit) { db.rollback(); } throw new SQLException(e.getMessage()); } finally { if (doCommit) { db.setAutoCommit(true); } } return result; }
From source file:org.seasar.dbflute.helper.jdbc.connection.DfDataSourceHandler.java
public void destroy() throws SQLException { try {//from ww w . ja v a2 s . c o m final Connection conn = getCachedConnection(); if (conn == null) { return; // if no cache, do nothing } if (!conn.getAutoCommit()) { _log.info("...rollback()"); conn.rollback(); } if (conn instanceof DfSimpleConnection) { _log.info("...closeReally()"); ((DfSimpleConnection) conn).closeReally(); } else { _log.info("...close()"); conn.close(); } } catch (SQLException ignored) { } finally { if (DfDataSourceContext.isExistDataSource()) { DfDataSourceContext.clearDataSource(); } } }
From source file:org.apache.roller.weblogger.business.startup.SQLScriptRunner.java
/** Run script, logs messages, and optionally throws exception on error */ public void runScript(Connection con, boolean stopOnError) throws SQLException { failed = false;/*from ww w. jav a2 s . c o m*/ errors = false; for (String command : commands) { // run each command try { Statement stmt = con.createStatement(); stmt.executeUpdate(command); if (!con.getAutoCommit()) { con.commit(); } // on success, echo command to messages successMessage(command); } catch (SQLException ex) { // add error message with text of SQL command to messages errorMessage("ERROR: SQLException executing SQL [" + command + "] : " + ex.getLocalizedMessage()); // add stack trace to messages StringWriter sw = new StringWriter(); ex.printStackTrace(new PrintWriter(sw)); errorMessage(sw.toString()); if (stopOnError) { failed = true; throw ex; } } } }
From source file:org.bytesoft.bytejta.supports.jdbc.RecoveredResource.java
public synchronized void forget(Xid[] xids) throws XAException { if (xids == null || xids.length == 0) { return;/*from w w w. j ava 2 s . co m*/ } String[] xidArray = new String[xids.length]; for (int i = 0; i < xids.length; i++) { Xid xid = xids[i]; byte[] globalTransactionId = xid.getGlobalTransactionId(); byte[] branchQualifier = xid.getBranchQualifier(); xidArray[i] = this.getIdentifier(globalTransactionId, branchQualifier); } Connection conn = null; PreparedStatement stmt = null; Boolean autoCommit = null; try { conn = this.dataSource.getConnection(); autoCommit = conn.getAutoCommit(); conn.setAutoCommit(false); stmt = conn.prepareStatement("delete from bytejta where xid = ?"); for (int i = 0; i < xids.length; i++) { stmt.setString(1, xidArray[i]); stmt.addBatch(); } stmt.executeBatch(); conn.commit(); } catch (Exception ex) { logger.error("Error occurred while forgetting resources."); try { conn.rollback(); } catch (Exception sqlEx) { logger.error("Error occurred while rolling back local resources.", sqlEx); } boolean tableExists = false; try { tableExists = this.isTableExists(conn); } catch (Exception sqlEx) { logger.warn("Error occurred while forgeting local resources.", ex); throw new XAException(XAException.XAER_RMFAIL); } if (tableExists) { throw new XAException(XAException.XAER_RMERR); } } finally { if (autoCommit != null) { try { conn.setAutoCommit(autoCommit); } catch (SQLException sqlEx) { logger.error("Error occurred while configuring attribute 'autoCommit'.", sqlEx); } } this.closeQuietly(stmt); this.closeQuietly(conn); } }
From source file:com.migratebird.database.impl.DefaultSQLHandler.java
public int executeUpdateAndCommit(String sql, DataSource dataSource) { logger.debug(sql);/*w w w. j av a2s . c om*/ if (!doExecuteUpdates) { // skip update return 0; } Statement statement = null; try { Connection connection = getConnection(dataSource); statement = connection.createStatement(); int nbChanges = statement.executeUpdate(sql); if (!connection.getAutoCommit()) { connection.commit(); } return nbChanges; } catch (Exception e) { throw new DatabaseException("Error while performing database update:\n" + sql, e); } finally { closeQuietly(statement); } }
From source file:com.rapidbackend.socialutil.install.dbinstall.SQLScriptRunner.java
/** Run script, logs messages, and optionally throws exception on error */ public void runScript(Connection con, boolean stopOnError) throws SQLException { failed = false;//from w w w.j a v a2 s. co m errors = false; for (String command : commands) { // run each command try { Statement stmt = con.createStatement(); stmt.executeUpdate(command); if (!con.getAutoCommit()) con.commit(); // on success, echo command to messages successMessage(command); } catch (SQLException ex) { // add error message with text of SQL command to messages errorMessage("ERROR: SQLException executing SQL [" + command + "] : " + ex.getLocalizedMessage()); // add stack trace to messages StringWriter sw = new StringWriter(); ex.printStackTrace(new PrintWriter(sw)); errorMessage(sw.toString()); if (stopOnError) { failed = true; throw ex; } } } }
From source file:com.quartzdesk.executor.common.spring.db.DataSourceScriptExecutorFactoryBean.java
/** * Applies the specified SQL init script to the database. * * @param con a JDBC connection./* w w w .ja v a 2 s . c om*/ * @param initScript the SQL init script to apply. */ private void applyInitScript(Connection con, Resource initScript) { URL initScriptUrl; try { initScriptUrl = initScript.getURL(); } catch (IOException e) { throw new RuntimeException("Error obtaining URL of SQL script resource: " + initScript); } boolean autoCommit = true; try { autoCommit = con.getAutoCommit(); DatabaseScriptExecutor scriptExecutor = new DatabaseScriptExecutor(); scriptExecutor.addScriptUrl(initScriptUrl); scriptExecutor.executeScripts(con); // if auto-commit disabled, we need to commit the changes if (!autoCommit) con.commit(); log.info("Successfully applied SQL script: {} to database.", initScriptUrl); } catch (SQLException e) { try { if (!autoCommit) con.rollback(); } catch (SQLException se) { log.warn("Error rolling-back connection: " + con, se); } throw new RuntimeException("Error applying SQL script: " + initScriptUrl, e); } }
From source file:org.apache.servicemix.nmr.audit.jdbc.JdbcAuditor.java
public int deleteExchangesByIds(String[] ids) throws AuditorException { Connection connection = null; boolean restoreAutoCommit = false; try {// w w w . j a v a2s . c om connection = dataSource.getConnection(); if (connection.getAutoCommit()) { connection.setAutoCommit(false); restoreAutoCommit = true; } for (int row = 0; row < ids.length; row++) { adapter.doRemoveData(connection, ids[row]); } connection.commit(); return ids.length; } catch (Exception e) { throw new AuditorException("Could not delete exchanges", e); } finally { close(connection, restoreAutoCommit); } }