List of usage examples for java.sql Connection getAutoCommit
boolean getAutoCommit() throws SQLException;
Connection
object. From source file:org.cloudgraph.rdb.service.RDBGraphService.java
public SnapshotMap commit(DataGraph[] dataGraphs, String username) { if (dataGraphs == null) throw new IllegalArgumentException("expected non-null 'dataGraphs' argument"); if (username == null) throw new IllegalArgumentException("expected non-null 'username' argument"); if (username.trim().length() == 0) throw new IllegalArgumentException("unexpected zero length 'username' argument"); SnapshotMap snapshotMap = new SnapshotMap(new Timestamp((new Date()).getTime())); Connection con = null; try {//from w w w . j ava 2 s . c o m if (log.isDebugEnabled()) log.debug("getting connection"); con = ProviderManager.instance().getConnection(); if (con.getAutoCommit()) { if (log.isDebugEnabled()) log.debug("turning off connection autocommit for multi graph commit"); con.setAutoCommit(false); } // TODO: make transaction isolation configurable con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); if (log.isDebugEnabled()) log.debug("using transaction isolation level " + con.getTransactionIsolation() + " for multi graph commit"); } catch (SQLException e2) { if (con != null) try { if (log.isDebugEnabled()) log.debug("closing connection"); con.close(); } catch (SQLException e) { log.error(e.getMessage(), e); } throw new DataAccessException(e2); } DataGraphDispatcher dispatcher = new GraphDispatcher(snapshotMap, username, con); try { dispatcher.commit(dataGraphs); con.commit(); return snapshotMap; } catch (DataAccessException e) { try { con.rollback(); } catch (SQLException e1) { log.error(e1.getMessage(), e1); } throw e; } catch (Throwable t) { try { con.rollback(); } catch (SQLException e) { log.error(e.getMessage(), e); } throw new DataAccessException(t); } finally { if (con != null) try { if (log.isDebugEnabled()) log.debug("closing connection"); con.close(); } catch (SQLException e) { log.error(e.getMessage(), e); } dispatcher.close(); } }
From source file:xbird.util.jdbc.QueryRunner.java
public int[] batch(Connection conn, String... sqls) throws SQLException { final boolean autoCommit = conn.getAutoCommit(); if (autoCommit) { conn.setAutoCommit(false);/* w w w .j a va 2s . co m*/ } Statement stmt = null; int[] rows = null; try { stmt = conn.createStatement(); for (int i = 0; i < sqls.length; i++) { verboseQuery(sqls[i], (Object[]) null); stmt.addBatch(sqls[i]); } rows = stmt.executeBatch(); conn.commit(); } catch (SQLException e) { DbUtils.rollback(conn); rethrow(e, sqls); } finally { close(stmt); } // change back commit mode. if (autoCommit) { conn.setAutoCommit(true); } return rows; }
From source file:com.tacitknowledge.util.migration.jdbc.JdbcMigrationLauncher.java
/** * Performs the application migration process in one go * * @param context the database context to run the patches in * @return the number of patches applied * @throws SQLException if an unrecoverable database error occurs while working with the patches table. * @throws MigrationException if an unrecoverable error occurs during the migration */// w w w . j a va 2 s . c o m protected int doMigrations(JdbcMigrationContext context) throws SQLException, MigrationException { PatchInfoStore patchTable = createPatchStore(context); lockPatchStore(context); // Now apply the patches int executedPatchCount = 0; try { // remember the auto-commit state, and turn auto-commit off Connection conn = context.getConnection(); boolean commitState = conn.getAutoCommit(); conn.setAutoCommit(false); // run the migrations try { executedPatchCount = migrationProcess.doMigrations(patchTable, context); } // restore autocommit state finally { if ((conn != null) && !conn.isClosed()) { conn.setAutoCommit(commitState); } } } catch (MigrationException me) { // If there was any kind of error, we don't want to eat it, but we do // want to unlock the patch store. So do that, then re-throw. patchTable.unlockPatchStore(); throw me; } // Do any post-patch tasks try { migrationProcess.doPostPatchMigrations(context); return executedPatchCount; } finally { try { patchTable.unlockPatchStore(); } catch (MigrationException e) { log.error("Error unlocking patch table: ", e); } } }
From source file:com.tacitknowledge.util.migration.jdbc.JdbcMigrationLauncher.java
/** * Performs the application rollbacks//from w w w . ja v a 2s. c om * * @param context the database context to run the patches in * @param rollbackLevel the level the system should rollback to * @param forceRollback is a boolean indicating if the application should ignore a check to see if all patches are rollbackable * @return the number of patches applied * @throws SQLException if an unrecoverable database error occurs while working with the patches table. * @throws MigrationException if an unrecoverable error occurs during the migration */ public int doRollbacks(JdbcMigrationContext context, int[] rollbackLevel, boolean forceRollback) throws SQLException, MigrationException { PatchInfoStore patchTable = createPatchStore(context); lockPatchStore(context); // Now apply the patches int executedPatchCount = 0; try { // remember the auto-commit state, and turn auto-commit off Connection conn = context.getConnection(); boolean commitState = conn.getAutoCommit(); conn.setAutoCommit(false); // run the rollbacks try { executedPatchCount = migrationProcess.doRollbacks(patchTable, rollbackLevel, context, forceRollback); } // restore autocommit state finally { if ((conn != null) && !conn.isClosed()) { conn.setAutoCommit(commitState); } } } catch (MigrationException me) { // If there was any kind of error, we don't want to eat it, but we do // want to unlock the patch store. So do that, then re-throw. patchTable.unlockPatchStore(); throw me; } // Do any post-patch tasks try { migrationProcess.doPostPatchMigrations(context); return executedPatchCount; } finally { try { patchTable.unlockPatchStore(); } catch (MigrationException e) { log.error("Error unlocking patch table: ", e); } } }
From source file:DbServletTrans.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { Connection conn = null; Statement stmt = null;/* w ww.j a v a2s . c o m*/ response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); out.println("<html><head><title>Using transactions</title></head><body>"); out.println("<h2>These SQL statements are part of a transaction</h2>"); out.println("CallableStatement.executeUpdate()"); out.println("<br><br>"); out.println("Statement.executeUpdate()"); out.println("<br><br>"); try { conn = pool.getConnection(); out.println("AutoCommit before setAutoCommit(): " + conn.getAutoCommit() + "<br><br>"); out.println("Transaction isolation level: "); switch (conn.getTransactionIsolation()) { case 0: out.println("TRANSACTION_NONE<br><br>"); break; case 1: out.println("TRANSACTION_READ_UNCOMMITTED<br><br>"); break; case 2: out.println("TRANSACTION_READ_COMMITTED<br><br>"); break; case 4: out.println("TRANSACTION_REPEATABLE_READ<br><br>"); break; case 8: out.println("TRANSACTION_SERIALIZABLE<br><br>"); break; default: out.println("UNKNOWN<br><br>"); } conn.setAutoCommit(false); CallableStatement cs = null; //Create an instance of the CallableStatement cs = conn.prepareCall("{call addEvent (?,?,?)}"); cs.setString(1, "Salisbury Beach 5-Miler"); cs.setString(2, "Salisbury MA"); cs.setString(3, "14-Aug-2003"); //Call the inherited PreparedStatement.executeUpdate() method cs.executeUpdate(); String sql = "update raceevent set racedate='13-Aug-2003' " + "where name='Salisbury Beach 5-Miler'"; int res = 0; stmt = conn.createStatement(); res = stmt.executeUpdate(sql); //commit the two SQL statements conn.commit(); } catch (Exception e) { try { //rollback the transaction in case of a problem conn.rollback(); } catch (SQLException sqle) { } throw new ServletException(e.getMessage()); } finally { try { if (stmt != null) stmt.close(); if (conn != null) conn.close();//this returns the Connection to the // Connection pool } catch (SQLException sqle) { } } out.println("</table></body></html>"); out.close(); }
From source file:org.opencms.db.oracle.CmsVfsDriver.java
/** * Writes the resource content with the specified resource id.<p> * //from ww w . ja v a 2 s . com * @param dbc the current database context * @param projectId the id of the current project * @param resourceId the id of the resource used to identify the content to update * @param contents the new content of the file * @param publishTag the publish tag if to be written to the online content * * @throws CmsDataAccessException if something goes wrong */ protected void internalWriteContent(CmsDbContext dbc, CmsUUID projectId, CmsUUID resourceId, byte[] contents, int publishTag) throws CmsDataAccessException { PreparedStatement stmt = null; PreparedStatement commit = null; Connection conn = null; ResultSet res = null; boolean wasInTransaction = false; try { conn = m_sqlManager.getConnection(dbc); if (projectId.equals(CmsProject.ONLINE_PROJECT_ID)) { stmt = m_sqlManager.getPreparedStatement(conn, projectId, "C_ORACLE_ONLINE_CONTENTS_UPDATECONTENT"); } else { stmt = m_sqlManager.getPreparedStatement(conn, projectId, "C_ORACLE_OFFLINE_CONTENTS_UPDATECONTENT"); } wasInTransaction = !conn.getAutoCommit(); if (!wasInTransaction) { conn.setAutoCommit(false); } // update the file content in the contents table stmt.setString(1, resourceId.toString()); if (projectId.equals(CmsProject.ONLINE_PROJECT_ID)) { stmt.setInt(2, publishTag); stmt.setInt(3, publishTag); } res = ((DelegatingResultSet) stmt.executeQuery()).getInnermostDelegate(); if (!res.next()) { throw new CmsDbEntryNotFoundException( Messages.get().container(Messages.LOG_READING_RESOURCE_1, resourceId)); } // write file content OutputStream output = CmsUserDriver.getOutputStreamFromBlob(res, "FILE_CONTENT"); output.write(contents, 0, contents.length); output.close(); if (!wasInTransaction) { commit = m_sqlManager.getPreparedStatement(conn, "C_COMMIT"); commit.execute(); m_sqlManager.closeAll(dbc, null, commit, null); } m_sqlManager.closeAll(dbc, null, stmt, res); // this is needed so the finally block works correctly commit = null; stmt = null; res = null; if (!wasInTransaction) { conn.setAutoCommit(true); } } catch (IOException e) { throw new CmsDbIoException( Messages.get().container(Messages.ERR_WRITING_TO_OUTPUT_STREAM_1, resourceId), e); } catch (SQLException e) { throw new CmsDbSqlException(org.opencms.db.generic.Messages.get().container( org.opencms.db.generic.Messages.ERR_GENERIC_SQL_1, CmsDbSqlException.getErrorQuery(stmt)), e); } finally { org.opencms.db.oracle.CmsSqlManager.closeAllInTransaction(m_sqlManager, dbc, conn, stmt, res, commit, wasInTransaction); } }
From source file:org.wso2.carbon.identity.application.authenticator.fido.dao.DeviceStoreDAO.java
/** * Remove registration entry once user store domain deleted. * * @param tenantId//from w ww. j a v a2 s .c om * @param userStoreName * @throws FIDOAuthenticatorServerException */ public void deleteRegistrationFromDomain(int tenantId, String userStoreName) throws FIDOAuthenticatorServerException { if (log.isDebugEnabled()) { log.debug("deleteRegistrationFromDomain inputs {tenantId: " + tenantId + ", userStoreName: " + userStoreName + "}"); } Connection connection = IdentityDatabaseUtil.getDBConnection(); PreparedStatement preparedStatement = null; try { preparedStatement = connection .prepareStatement(FIDOAuthenticatorConstants.SQLQueries.DELETE_DEVICE_REGISTRATION_FROM_DOMAIN); preparedStatement.setInt(1, tenantId); preparedStatement.setString(2, userStoreName.toUpperCase()); preparedStatement.executeUpdate(); if (!connection.getAutoCommit()) { connection.commit(); } } catch (SQLException e) { throw new FIDOAuthenticatorServerException("Error executing remove registrations SQL on domain delete: " + FIDOAuthenticatorConstants.SQLQueries.DELETE_DEVICE_REGISTRATION_FROM_DOMAIN, e); } finally { IdentityDatabaseUtil.closeAllConnections(connection, null, preparedStatement); } }
From source file:org.opennms.netmgt.linkd.DbAtInterfaceEntry.java
/** * Updates the interface information in the configured database. If the * interface does not exist the a new row in the table is created. If the * element already exists then it's current row is updated as * needed based upon the current changes to the node. *///from w w w. j a v a2s . co m void store() throws SQLException { if (m_changed != 0 || m_fromDb == false) { Connection db = null; try { db = DataSourceFactory.getInstance().getConnection(); store(db); if (db.getAutoCommit() == false) db.commit(); } finally { try { if (db != null) db.close(); } catch (SQLException e) { LogUtils.warnf(this, e, "Exception closing JDBC connection"); } } } return; }
From source file:org.executequery.databaseobjects.impl.AbstractDatabaseObject.java
/** * Retrieves the data row count for this object (where applicable). * * @return the data row count for this object *//*w w w . ja v a 2 s.c o m*/ public int getDataRowCount() throws DataSourceException { if (dataRowCount != -1) { return dataRowCount; } ResultSet rs = null; Statement stmnt = null; Connection connection = null; try { connection = getHost().getTemporaryConnection(); stmnt = connection.createStatement(); rs = stmnt.executeQuery(recordCountQueryString()); if (rs.next()) { dataRowCount = rs.getInt(1); } if (!connection.getAutoCommit()) { connection.commit(); } return dataRowCount; } catch (SQLException e) { throw new DataSourceException(e); } finally { releaseResources(stmnt, rs); releaseResources(connection); } }
From source file:org.wso2.carbon.dashboard.portal.core.datasource.DSDataSourceManager.java
/** * To create the gadget usage table//www . j av a 2 s . c o m * * @throws DashboardPortalException */ private void createUsageDatabase() throws DashboardPortalException { Connection conn = null; try { conn = dataSource.getConnection(); statement = conn.createStatement(); executeScript(); if (!conn.getAutoCommit()) { conn.commit(); } if (log.isDebugEnabled()) { log.debug("Gadget usage table is created successfully."); } } catch (SQLException e) { String msg = "Failed to create database tables for dashboard server. " + e.getMessage(); throw new DashboardPortalException(msg, e); } finally { closeDatabaseResources(conn, statement, null); } }