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.wso2.carbon.dashboard.portal.core.datasource.DSDataSourceManager.java

/**
 * To update the databse when a dashboard is deleted
 *
 * @param tenantId    Id of the tenant which the dashboard belongs to
 * @param dashboardId Id of the dashboard
 * @throws DashboardPortalException//from   w  w w.jav a  2  s .  c o m
 */
public void updateAfterDeletingDashboard(int tenantId, String dashboardId) throws DashboardPortalException {
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    try {
        connection = dataSource.getConnection();
        preparedStatement = connection.prepareStatement(DataSourceConstants.SQL_DELETE_DASHBOARD_OPERATION);
        preparedStatement.setInt(1, tenantId);
        preparedStatement.setString(2, dashboardId);
        preparedStatement.executeUpdate();
        if (!dashboardId.contains("$")) {
            preparedStatement = connection
                    .prepareStatement(DataSourceConstants.SQL_DELETE_ALL_DASHBOARD_OPERATION);
            preparedStatement.setInt(1, tenantId);
            preparedStatement.setString(2, dashboardId + "$%");
            preparedStatement.executeUpdate();
        }
        if (!connection.getAutoCommit()) {
            connection.commit();
        }
    } catch (SQLException e) {
        log.error("Cannot insert the gadget usage info ", e);
    } finally {
        closeDatabaseResources(connection, preparedStatement, null);
    }
}

From source file:com.glaf.core.util.DBUtils.java

public static void createIndex(Connection connection, String tableName, String columnName, String indexName) {
    DatabaseMetaData dbmd = null;
    Statement stmt = null;//from w  w w  . j  a  v a 2s . c om
    ResultSet rs = null;
    boolean hasIndex = false;
    boolean autoCommit = false;
    try {
        autoCommit = connection.getAutoCommit();
        dbmd = connection.getMetaData();
        rs = dbmd.getIndexInfo(null, null, tableName, false, false);
        while (rs.next()) {
            String col = rs.getString("COLUMN_NAME");
            if (StringUtils.equalsIgnoreCase(columnName, col)) {
                hasIndex = true;
                break;
            }
        }
        JdbcUtils.close(rs);

        if (!hasIndex) {
            String sql = " create index " + indexName.toUpperCase() + " on " + tableName + " (" + columnName
                    + ") ";
            connection.setAutoCommit(false);
            stmt = connection.createStatement();
            stmt.executeUpdate(sql);
            JdbcUtils.close(stmt);
            connection.commit();
            connection.setAutoCommit(autoCommit);
        }
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        JdbcUtils.close(rs);
        JdbcUtils.close(stmt);
    }
}

From source file:org.springframework.orm.hibernate3.SessionFactoryBuilderSupport.java

/**
 * Execute the given schema script on the given JDBC Connection.
 * <p>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/*from  ww  w .j  a v a  2s  .c o  m*/
 */
protected void executeSchemaScript(Connection con, String... sql) throws SQLException {
    if (sql != null && sql.length > 0) {
        boolean oldAutoCommit = con.getAutoCommit();
        if (!oldAutoCommit) {
            con.setAutoCommit(true);
        }
        try {
            Statement stmt = con.createStatement();
            try {
                for (String sqlStmt : sql) {
                    executeSchemaStatement(stmt, sqlStmt);
                }
            } finally {
                JdbcUtils.closeStatement(stmt);
            }
        } finally {
            if (!oldAutoCommit) {
                con.setAutoCommit(false);
            }
        }
    }
}

From source file:org.executequery.databaseobjects.impl.DefaultDatabaseTable.java

private int applyTableDefinitionChanges() throws DataSourceException {

    Statement stmnt = null;//from  w ww. j a v  a  2 s . co m

    try {

        String changes = getModifiedSQLText();
        if (StringUtils.isBlank(changes)) {

            // bail if we're empty here

            return 1;
        }

        int result = 0;
        String[] queries = changes.split(StatementGenerator.END_DELIMITER);

        Connection connection = getHost().getConnection();
        stmnt = connection.createStatement();

        for (int i = 0; i < queries.length; i++) {

            String query = queries[i].trim();
            if (StringUtils.isNotBlank(query)) {

                result += stmnt.executeUpdate(query);
            }

        }

        if (!connection.getAutoCommit()) {

            connection.commit();
        }

        // set to reset for the next call
        reset();

        return result;

    } catch (SQLException e) {

        throw new DataSourceException(e);

    } finally {

        releaseResources(stmnt);
    }
}

From source file:org.apache.sqoop.hcat.HCatalogTestUtils.java

private void loadSqlTable(Connection conn, String table, int count, ColumnGenerator... extraCols)
        throws Exception {
    PreparedStatement statement = conn.prepareStatement(getSqlInsertTableStatement(table, extraCols),
            ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
    try {//from  w ww.j  a  va 2  s. c  o  m
        for (int i = 0; i < count; ++i) {
            statement.setObject(1, i, Types.INTEGER);
            statement.setObject(2, "textfield" + i, Types.VARCHAR);
            for (int j = 0; j < extraCols.length; ++j) {
                statement.setObject(j + 3, extraCols[j].getDBValue(i), extraCols[j].getSqlType());
            }
            statement.executeUpdate();
        }
        if (!conn.getAutoCommit()) {
            conn.commit();
        }
    } finally {
        statement.close();
    }
}

From source file:org.apache.openjpa.jdbc.schema.SchemaTool.java

/**
 * Executes the given array of non-selecting SQL statements, correctly
 * logging the SQL calls and optionally ignoring errors.
 *
 * @return true if there was SQL to execute and the calls were
 * successful, false otherwise//from w ww.  j  ava 2s.c o  m
 */
protected boolean executeSQL(String[] sql) throws SQLException {
    // if no sql, probably b/c dictionary doesn't support operation
    if (sql.length == 0)
        return false;

    boolean err = false;
    if (_writer == null) {
        // this is outside the try-catch because a failure here is
        // really bad, and should not be ignored.
        Connection conn = _ds.getConnection();
        Statement statement = null;
        boolean wasAuto = true;
        try {
            wasAuto = conn.getAutoCommit();
            if (!wasAuto)
                conn.setAutoCommit(true);
            for (int i = 0; i < sql.length; i++) {
                try {
                    // some connections require that rollback be
                    // called on the connection before any DDL statements
                    // can be run on it, even when autocommit is on.
                    // This is sometimes because the connection does not
                    // allow DDL statements when there are multiple
                    // commands issued on the connection, and the
                    // connection pool may have issued some validation SQL.
                    try {
                        conn.rollback();
                    } catch (Exception e) {
                    }

                    statement = conn.createStatement();
                    statement.executeUpdate(sql[i]);

                    // some connections seem to require an explicit
                    // commit for DDL statements, even when autocommit
                    // is on. The DataDirect drivers seem to suffer from
                    // this limitation.
                    try {
                        conn.commit();
                    } catch (Exception e) {
                    }
                } catch (SQLException se) {
                    err = true;
                    handleException(se);
                } finally {
                    if (statement != null)
                        try {
                            statement.close();
                        } catch (SQLException se) {
                        }
                }
            }
        } finally {
            if (!wasAuto)
                conn.setAutoCommit(false);
            try {
                conn.close();
            } catch (SQLException se) {
            }
        }
    } else {
        for (int i = 0; i < sql.length; i++)
            _writer.println(sql[i] + _sqlTerminator);
        _writer.flush();
    }

    return !err;
}

From source file:dk.netarkivet.archive.arcrepositoryadmin.ReplicaCacheDatabase.java

/**
 * This method is used to update the status for the checksums for all replicafileinfo entries. <br/>
 * <br/>/*  w  w  w .j ava  2  s  .c om*/
 * For each file in the database, the checksum vote is made in the following way. <br/>
 * Each entry in the replicafileinfo table containing the file is retrieved. All the unique checksums are retrieved,
 * e.g. if a checksum is found more than one, then it is ignored. <br/>
 * If only one unique checksum is found, then if must be the correct one, and all the replicas with this file will
 * have their checksum_status set to 'OK'. <br/>
 * If more than one checksum is found, then a vote for the correct checksum is performed. This is done by counting
 * the amount of time each of the unique checksum is found among the replicafileinfo entries for the current file.
 * The checksum with most votes is chosen as the correct one, and the checksum_status for all the replicafileinfo
 * entries with this checksum is set to 'OK', whereas the replicafileinfo entries with a different checksum is set
 * to 'CORRUPT'. <br/>
 * If no winner is found then a warning and a notification is issued, and the checksum_status for all the
 * replicafileinfo entries with for the current file is set to 'UNKNOWN'. <br/>
 */
public void updateChecksumStatus() {
    log.info("UpdateChecksumStatus operation commencing");
    Connection con = ArchiveDBConnection.get();
    boolean autoCommit = true;
    try {
        autoCommit = con.getAutoCommit();
        // Set checksum_status to 'OK' where there is the same
        // checksum across all replicas.
        DBUtils.executeSQL(con, updateChecksumStatusSql);

        // Get all the fileids that need processing.
        // Previously: "SELECT file_id FROM file"
        Iterator<Long> fileIdsIterator = DBUtils.selectLongIterator(con, selectForFileChecksumVotingSql);
        // For each fileid
        while (fileIdsIterator.hasNext()) {
            long fileId = fileIdsIterator.next();
            ReplicaCacheHelpers.fileChecksumVote(fileId, con);
        }
    } catch (SQLException e) {
        throw new IOFailure("Error getting auto commit.\n" + ExceptionUtils.getSQLExceptionCause(e), e);
    } finally {
        try {
            con.setAutoCommit(autoCommit);
        } catch (SQLException e) {
            log.error("Could not change auto commit back to default!");
        }
        ArchiveDBConnection.release(con);
    }
    log.info("UpdateChecksumStatus operation completed!");
}

From source file:org.apache.openjpa.jdbc.kernel.TableJDBCSeq.java

/**
 * Inserts the initial sequence column into the database.
 * //w  w w  .j a va 2 s .c  o  m
 * @param mapping
 *            ClassMapping for the class whose sequence column will be
 *            updated
 * @param conn
 *            Connection used issue SQL statements.
 */
private void insertSequence(ClassMapping mapping, Connection conn) throws SQLException {

    if (_log.isTraceEnabled())
        _log.trace(_loc.get("insert-seq"));

    Object pk = getPrimaryKey(mapping);
    if (pk == null)
        throw new InvalidStateException(_loc.get("bad-seq-type", getClass(), mapping));

    DBDictionary dict = _conf.getDBDictionaryInstance();
    DBIdentifier tableName = resolveTableIdentifier(mapping, _pkColumn.getTable());
    SQLBuffer insert = new SQLBuffer(dict).append("INSERT INTO ").append(tableName).append(" (")
            .append(_pkColumn).append(", ").append(_seqColumn).append(") VALUES (").appendValue(pk, _pkColumn)
            .append(", ").appendValue(_intValue, _seqColumn).append(")");

    boolean wasAuto = conn.getAutoCommit();
    if (!wasAuto && !suspendInJTA())
        conn.setAutoCommit(true);

    PreparedStatement stmnt = null;
    try {
        stmnt = prepareStatement(conn, insert);
        dict.setTimeouts(stmnt, _conf, true);
        executeUpdate(_conf, conn, stmnt, insert, RowImpl.ACTION_INSERT);
    } finally {
        if (stmnt != null)
            try {
                stmnt.close();
            } catch (SQLException se) {
            }
        if (!wasAuto && !suspendInJTA())
            conn.setAutoCommit(false);
    }
}

From source file:ca.inverse.sogo.engine.source.SOGoUtilities.java

/**
 * This method is used to guess the best database driver
 * based on the supplied URI. The format is usually:
 * /*  w w  w.j ava2  s.  c om*/
 * jdbc:postgresql:...
 * jdbc:oracle:thin:...
 * 
 * It then initialize the driver with the proper parameters and
 * establish a database connection, which is returned.
 */
public static Connection initDatabaseDriver(SOGoSyncSource source, FunambolLogger log) {
    Connection con;
    Properties props;
    String s, uri;
    int a, b;

    props = new Properties();
    uri = source.getDatabaseURL();
    a = uri.indexOf(':');
    b = uri.indexOf(':', a + 1);
    s = uri.substring(a + 1, b);

    if (s.equalsIgnoreCase("oracle")) {
        s = "oracle.jdbc.OracleDriver";

        // For Oracle, we try to load big strings as CLOB. This works
        // with the ojdbc14.jar (Oracle 10g 10.1.0.2.0) driver.
        props.put("SetBigStringTryClob", "true");
    } else if (s.equalsIgnoreCase("mysql")) {
        s = "com.mysql.jdbc.Driver";
    } else {
        s = "org.postgresql.Driver";
    }

    props.put("user", source.getDatabaseUsername());
    props.put("password", source.getDatabasePassword());

    try {
        log.info("Loading the JDBC driver for URL: " + source.getDatabaseURL());
        Class.forName(s);

        con = DriverManager.getConnection(uri, props);

        // MySQL driver defaults to autocommit, so make sure it's turned off
        if (con.getAutoCommit()) {
            con.setAutoCommit(false);
        }

        return con;
    } catch (Exception e) {
        log.error("Couldn't find the driver! (" + s + ") or connect to the database: " + e.toString(), e);
    }

    return null;
}

From source file:org.wso2.carbon.apimgt.impl.dao.CertificateMgtDAO.java

/**
 * To update an already existing client certificate.
 *
 * @param certificate : Specific certificate.
 * @param alias       : Alias of the certificate.
 * @param tier        : Name of tier related with the certificate.
 * @param tenantId    : ID of the tenant.
 * @return true if the update succeeds, unless false.
 * @throws CertificateManagementException Certificate Management Exception.
 *///from   ww w.ja v  a  2  s  . co  m
public boolean updateClientCertificate(String certificate, String alias, String tier, int tenantId)
        throws CertificateManagementException {
    boolean result = false;
    Connection connection = null;
    PreparedStatement preparedStatement = null;

    List<ClientCertificateDTO> clientCertificateDTOList = getClientCertificates(tenantId, alias, null);
    ClientCertificateDTO clientCertificateDTO;

    if (clientCertificateDTOList.size() == 0) {
        if (log.isDebugEnabled()) {
            log.debug("Client certificate update request is received for a non-existing alias " + alias + " of "
                    + "tenant " + tenantId);
        }
        return false;
    }
    clientCertificateDTO = clientCertificateDTOList.get(0);
    if (StringUtils.isNotEmpty(certificate)) {
        clientCertificateDTO.setCertificate(certificate);
    }
    if (StringUtils.isNotEmpty(tier)) {
        clientCertificateDTO.setTierName(tier);
    }
    try {
        connection = APIMgtDBUtil.getConnection();
        initialAutoCommit = connection.getAutoCommit();
        connection.setAutoCommit(false);
        deleteClientCertificate(null, alias, tenantId, connection);
        addClientCertificate(clientCertificateDTO.getCertificate(), clientCertificateDTO.getApiIdentifier(),
                alias, clientCertificateDTO.getTierName(), tenantId, connection);
        connection.commit();
        result = true;
    } catch (SQLException e) {
        handleConnectionRollBack(connection);
        handleException("Error while updating client certificate for the API for the alias " + alias, e);
    } finally {
        APIMgtDBUtil.setAutoCommit(connection, initialAutoCommit);
        APIMgtDBUtil.closeAllConnections(preparedStatement, connection, null);
    }
    return result;
}