Example usage for java.sql Connection getAutoCommit

List of usage examples for java.sql Connection getAutoCommit

Introduction

In this page you can find the example usage for java.sql Connection getAutoCommit.

Prototype

boolean getAutoCommit() throws SQLException;

Source Link

Document

Retrieves the current auto-commit mode for this Connection object.

Usage

From source file:org.ralasafe.userType.UserTypeManagerImpl.java

public void deleteUserType(String name) {
    loadIntoMemory();//  w  w  w. j  av a 2s . co  m

    Collection applications = getApplications(name);

    Connection conn = null;
    boolean autoCommit = true;
    try {
        conn = DBPower.getConnection(table.getId());
        autoCommit = conn.getAutoCommit();
        conn.setAutoCommit(false);

        // drop application's user-role tables
        for (Iterator itr = applications.iterator(); itr.hasNext();) {
            Application application = (Application) itr.next();
            String dropSql = DBUtil.userRoleTableDropSql(application.getName(), name);
            try {
                DBUtil.exec(conn, dropSql);
            } catch (SQLException e) {
                logger.error("Failed to delete table: " + dropSql);
            }
        }

        // delete app-usertype relationship
        ApplicationUserType appUserTypeHint = new ApplicationUserType();
        appUserTypeHint.setUserTypeName(name);
        applicationUserTypeDeletor.delete(conn, userTypeNameAppUserTypeTableWhereEmt, appUserTypeHint);

        // delete UserType
        UserType userTypeHint = new UserType();
        userTypeHint.setName(name);
        deletor.deleteByIdColumns(conn, userTypeHint);

        conn.commit();
    } catch (SQLException e) {
        DBUtil.rollback(conn);
        throw new DBLevelException(e);
    } finally {
        DBUtil.setCommitMode(conn, autoCommit);
        DBUtil.close(conn);
    }

    //userTypeMap.remove(name);
    changed = true;
    // notify Factory
    Factory.userTypeChanged(name);
}

From source file:org.seasar.dbflute.helper.jdbc.connection.DfDataSourceHandler.java

public void commit() throws SQLException {
    Connection conn = null;
    try {// ww  w. j  a  v  a 2 s .c om
        conn = getCachedConnection();
        if (conn == null) {
            return; // if no cache, do nothing
        }
        if (!conn.getAutoCommit()) {
            _log.info("...commit()");
            conn.commit();
        }
    } catch (SQLException e) {
        String msg = "Failed to commit the conection: conn=" + conn;
        throw new DfJDBCException(msg, e);
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException ignored) {
            }
        }
    }
}

From source file:org.apache.servicemix.nmr.audit.jdbc.JdbcAuditor.java

public void exchangeSent(Exchange exchange) {
    try {/*from ww  w. j  av  a  2s.c  o m*/
        String id = exchange.getId();
        Connection connection = null;
        boolean restoreAutoCommit = false;
        try {
            connection = dataSource.getConnection();
            if (connection.getAutoCommit()) {
                connection.setAutoCommit(false);
                restoreAutoCommit = true;
            }
            store(connection, id, getDataForExchange(exchange));
            connection.commit();
        } finally {
            close(connection, restoreAutoCommit);
        }
    } catch (Exception e) {
        log.error("Could not persist exchange", e);
    }
}

From source file:org.apache.cayenne.datasource.UnmanagedPoolingDataSource.java

/**
 * Updates connection state to a default state.
 *//* w w w  .  j  a  v a  2  s.  com*/
Connection resetState(Connection c) throws SQLException {

    // TODO: tx isolation level?

    if (!c.getAutoCommit()) {

        try {
            c.setAutoCommit(true);
        } catch (SQLException e) {
            UnmanagedPoolingDataSource.sybaseAutoCommitPatch(c, e, true);
        }
    }

    c.clearWarnings();
    return c;
}

From source file:org.apache.servicemix.nmr.audit.jdbc.JdbcAuditor.java

public void afterPropertiesSet() throws Exception {
    if (this.dataSource == null) {
        throw new IllegalArgumentException("dataSource should not be null");
    }/*  w w  w  . jav a2  s.c  o  m*/
    if (statements == null) {
        statements = new Statements();
        statements.setStoreTableName(tableName);
    }
    Connection connection = null;
    boolean restoreAutoCommit = false;
    try {
        connection = getDataSource().getConnection();
        if (connection.getAutoCommit()) {
            connection.setAutoCommit(false);
            restoreAutoCommit = true;
        }
        adapter = JDBCAdapterFactory.getAdapter(connection);
        if (statements == null) {
            statements = new Statements();
            statements.setStoreTableName(tableName);
        }
        adapter.setStatements(statements);
        if (createDataBase) {
            adapter.doCreateTables(connection);
        }
        connection.commit();
    } catch (SQLException e) {
        throw (IOException) new IOException("Exception while creating database").initCause(e);
    } finally {
        close(connection, restoreAutoCommit);
    }
    this.tccl = Thread.currentThread().getContextClassLoader();
}

From source file:org.hyperic.hq.plugin.mysql_stats.MySqlStatsMeasurementPlugin.java

protected Connection getCachedConnection(Metric metric) throws SQLException {
    Connection conn = super.getCachedConnection(metric);
    final boolean autocommit = conn.getAutoCommit();
    if (!autocommit) {
        conn.setAutoCommit(true);//from   ww w .j av a  2  s.co  m
    }
    return conn;
}

From source file:org.opencms.db.oracle.CmsUserDriver.java

/**
 * Updates the given user information entry.<p>
 * // w w w  .  j  a va  2  s  .  c  o m
 * @param dbc the current database context
 * @param userId the id of the user to update
 * @param key the user info entry key
 * @param value the user info entry value
 * 
 * @throws CmsDataAccessException if something goes wrong
 */
protected void internalUpdateUserInfoData(CmsDbContext dbc, CmsUUID userId, String key, Object value)
        throws CmsDataAccessException {

    PreparedStatement stmt = null;
    PreparedStatement commit = null;
    ResultSet res = null;
    Connection conn = null;

    boolean wasInTransaction = false;

    try {
        // get connection
        conn = m_sqlManager.getConnection(dbc);
        wasInTransaction = !conn.getAutoCommit();
        if (!wasInTransaction) {
            conn.setAutoCommit(false);
        }

        // update user_info in this special way because of using blob
        stmt = m_sqlManager.getPreparedStatement(conn, "C_ORACLE_USERDATA_UPDATE_2");
        stmt.setString(1, userId.toString());
        stmt.setString(2, key);
        res = ((DelegatingResultSet) stmt.executeQuery()).getInnermostDelegate();
        if (!res.next()) {
            throw new CmsDbEntryNotFoundException(
                    Messages.get().container(Messages.ERR_NO_USER_WITH_ID_1, userId));
        }
        // write serialized user info 
        OutputStream output = getOutputStreamFromBlob(res, "DATA_VALUE");
        output.write(CmsDataTypeUtil.dataSerialize(value));
        output.close();
        value = null;

        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 (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);
    } catch (IOException e) {
        throw new CmsDbIoException(Messages.get().container(Messages.ERR_SERIALIZING_USER_DATA_1, userId), e);
    } finally {
        org.opencms.db.oracle.CmsSqlManager.closeAllInTransaction(m_sqlManager, dbc, conn, stmt, res, commit,
                wasInTransaction);
    }
}

From source file:org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy.java

/**
 * Check the default connection properties (auto-commit, transaction isolation),
 * keeping them to be able to expose them correctly without fetching an actual
 * JDBC Connection from the target DataSource.
 * <p>This will be invoked once on startup, but also for each retrieval of a
 * target Connection. If the check failed on startup (because the database was
 * down), we'll lazily retrieve those settings.
 * @param con the Connection to use for checking
 * @throws SQLException if thrown by Connection methods
 *///  ww  w . j a v a  2s  .  com
protected synchronized void checkDefaultConnectionProperties(Connection con) throws SQLException {
    if (this.defaultAutoCommit == null) {
        this.defaultAutoCommit = con.getAutoCommit();
    }
    if (this.defaultTransactionIsolation == null) {
        this.defaultTransactionIsolation = con.getTransactionIsolation();
    }
}

From source file:org.unitils.core.dbsupport.DefaultSQLHandler.java

public int executeUpdateAndCommit(String sql) {
    logger.debug(sql);/*from  w  w w.j a va  2s  .co  m*/

    if (!doExecuteUpdates) {
        // skip update
        return 0;
    }
    Connection connection = null;
    Statement statement = null;
    try {
        connection = dataSource.getConnection();
        statement = connection.createStatement();
        int nbChanges = statement.executeUpdate(sql);
        if (!connection.getAutoCommit()) {
            connection.commit();
        }
        return nbChanges;

    } catch (Exception e) {
        throw new UnitilsException("Error while performing database update: " + sql, e);
    } finally {
        closeQuietly(connection, statement, null);
    }
}

From source file:corner.migration.services.impl.MigrationServiceImpl.java

/**
 * Execute the given schema script on the given JDBC Connection.
 * <p>//  w  ww .  j  av  a 2 s . c om
 * Note that the default implementation will log unsuccessful statements and
 * continue to execute. Override the <code>executeSchemaStatement</code>
 * method to treat failures differently.
 * 
 * @param con
 *            the JDBC Connection to execute the script on
 * @param sql
 *            the SQL statements to execute
 * @throws SQLException
 *             if thrown by JDBC methods
 * @see #executeSchemaStatement
 * @param con
 *            the JDBC Connection to execute the script on
 * @param sql
 *            the SQL statements to execute
 * @throws SQLException
 *             if thrown by JDBC methods
 */
protected void executeSchemaScript(Connection con, String... sql) throws SQLException {
    if (sql != null && sql.length > 0) {
        boolean oldAutoCommit = con.getAutoCommit();
        if (!oldAutoCommit) {
            con.setAutoCommit(false);
        }
        try {
            Statement stmt = con.createStatement();
            try {
                for (int i = 0; i < sql.length; i++) {
                    try {
                        logger.info("[db-upgrade] " + sql[i]);
                        executeSchemaStatement(stmt, sql[i]);
                    } catch (SQLException se) {
                        logger.error("[db-upgrade]" + se.toString(), se);
                        throw se;
                    }
                }
            } finally {
                JdbcUtils.closeStatement(stmt);
            }
        } finally {
            if (!oldAutoCommit) {
                con.setAutoCommit(false);
            }
        }
    }
}