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.gsoft.admin.ScriptRunner.java

/**
 * Runs an SQL script (read in using the Reader parameter)
 * //from w  w  w.  ja v  a  2s. co m
 * @param reader
 *            - the source of the script
 */
public void runScript(Reader reader) throws IOException, SQLException {
    try {
        Connection connection = this.dataSource.getConnection();
        boolean originalAutoCommit = connection.getAutoCommit();
        try {
            if (originalAutoCommit != this.autoCommit) {
                connection.setAutoCommit(this.autoCommit);
            }
            runScript(connection, reader);
        } finally {
            connection.setAutoCommit(originalAutoCommit);
        }
    } catch (IOException e) {
        throw e;
    } catch (SQLException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException("Error running script.  Cause: " + e, e);
    }
}

From source file:com.migratebird.database.impl.DefaultSQLHandler.java

/**
 * Starts a transaction by turning of auto commit.
 * Make sure to call endTransaction at the end of the transaction
 *
 * @param dataSource The data source, not null
 *///from  w  w  w.j av a 2 s  .  c  om
public void startTransaction(DataSource dataSource) {
    Connection connection = getConnection(dataSource);
    try {
        if (connection.getAutoCommit()) {
            connection.setAutoCommit(false);
        }
    } catch (Exception e) {
        throw new DatabaseException("Unable to start transaction.", e);
    }
}

From source file:net.sf.jasperreports.data.hibernate.HibernateConnectionProvider.java

@Override
public Connection getConnection() throws SQLException {

    if (log.isTraceEnabled())
        log.trace("total checked-out connections: " + checkedOut);

    synchronized (pool) {
        if (!pool.isEmpty()) {
            int last = pool.size() - 1;
            if (log.isTraceEnabled()) {
                log.trace("using pooled JDBC connection, pool size: " + last);
                checkedOut++;/*from  w w  w .j av a 2 s  .  co  m*/
            }
            Connection pooled = pool.remove(last);
            if (isolation != null)
                pooled.setTransactionIsolation(isolation.intValue());
            if (pooled.getAutoCommit() != autocommit)
                pooled.setAutoCommit(autocommit);
            return pooled;
        }
    }

    log.debug("opening new JDBC connection");
    Connection conn = driver.connect(url, connectionProps);
    if (isolation != null)
        conn.setTransactionIsolation(isolation.intValue());
    if (conn.getAutoCommit() != autocommit)
        conn.setAutoCommit(autocommit);

    if (log.isDebugEnabled()) {
        log.debug("created connection to: " + url + ", Isolation Level: " + conn.getTransactionIsolation());
    }
    if (log.isTraceEnabled())
        checkedOut++;

    return conn;
}

From source file:chh.utils.db.source.common.JdbcClient.java

public void executeInsertQuery(String query, List<List<Column>> columnLists) {
    Connection connection = null;
    try {/*  ww w .j  ava  2s  .  c  om*/
        connection = connectionProvider.getConnection();
        boolean autoCommit = connection.getAutoCommit();
        if (autoCommit) {
            connection.setAutoCommit(false);
        }

        LOG.debug("Executing query {}", query);

        PreparedStatement preparedStatement = connection.prepareStatement(query);
        if (queryTimeoutSecs > 0) {
            preparedStatement.setQueryTimeout(queryTimeoutSecs);
        }

        for (List<Column> columnList : columnLists) {
            setPreparedStatementParams(preparedStatement, columnList);
            preparedStatement.addBatch();
        }

        int[] results = preparedStatement.executeBatch();
        if (Arrays.asList(results).contains(Statement.EXECUTE_FAILED)) {
            connection.rollback();
            throw new RuntimeException(
                    "failed at least one sql statement in the batch, operation rolled back.");
        } else {
            try {
                connection.commit();
            } catch (SQLException e) {
                throw new RuntimeException("Failed to commit insert query " + query, e);
            }
        }
    } catch (SQLException e) {
        throw new RuntimeException("Failed to execute insert query " + query, e);
    } finally {
        closeConnection(connection);
    }
}

From source file:uk.ac.cam.caret.sakai.rwiki.component.model.impl.SQLScriptMigration.java

/**
 * borrowed from LocalSessionFactoryBean in spring
 * /*from  w  ww . j a v a 2  s  . c o m*/
 * @param con
 * @param sql
 * @throws SQLException
 */
protected void executeSchemaScript(Connection con, String[] sql, boolean newdb) throws SQLException {
    if (sql != null && sql.length > 0) {
        boolean oldAutoCommit = con.getAutoCommit();
        if (!oldAutoCommit) {
            con.setAutoCommit(true);
        }
        try {
            Statement stmt = con.createStatement(); // validated as closing
            try {
                for (int i = 0; i < sql.length; i++) {
                    if (sql[i].startsWith("message")) {
                        log.info("Data Migration " + sql[i]);
                    } else {
                        log.debug("Executing data migration statement: " + sql[i]);
                        try {
                            long start = System.currentTimeMillis();
                            int l = stmt.executeUpdate(sql[i]);
                            log.debug("   Done " + l + " rows in " + (System.currentTimeMillis() - start)
                                    + " ms");
                        } catch (SQLException ex) {
                            if (newdb) {
                                log.debug("Unsuccessful data migration statement: " + sql[i]);
                                log.debug("Cause: " + ex.getMessage());
                            } else {
                                log.warn("Unsuccessful data migration statement: " + sql[i]);
                                log.debug("Cause: " + ex.getMessage());
                            }
                        }
                    }
                }
            } finally {
                JdbcUtils.closeStatement(stmt);
            }
        } finally {
            if (!oldAutoCommit) {
                con.setAutoCommit(false);
            }
        }
    }
}

From source file:org.apache.openaz.xacml.admin.XacmlJDBCConnectionPool.java

@Override
public synchronized void releaseConnection(Connection conn) {
    if (conn == null || !initialized) {
        return;/*from  w ww  .j  av a2s . c  om*/
    }
    /* Try to roll back if necessary */
    try {
        if (!conn.getAutoCommit()) {
            conn.rollback();
        }
    } catch (SQLException e) {
        /* Roll back failed, close and discard connection */
        try {
            conn.close();
        } catch (SQLException e1) { // NOPMD
            /* Nothing needs to be done */
        }
        reservedConnections.remove(conn);
        return;
    }
    reservedConnections.remove(conn);
    availableConnections.add(conn);
}

From source file:org.jboss.dashboard.database.NonPooledDataSource.java

protected boolean getAutoCommit(Connection conn) {
    try {/* w w  w .  j ava  2s . c om*/
        return conn.getAutoCommit();
    } catch (SQLException e) {
        // Ignore problems when trying to get autocommit.
        // In some environments (Presidencia - Informix) when trying to get autocommit an exception is thrown.
        log.debug("Can not get autocommit.", e);
        return true;
    }
}

From source file:com.concursive.connect.web.modules.badges.dao.BadgeLogoFile.java

public boolean insert(Connection db) throws SQLException {
    boolean result = false;
    // The required linkModuleId
    linkModuleId = Constants.BADGE_FILES;
    // Determine if the database is in auto-commit mode
    boolean doCommit = false;
    try {/*w w  w .j  a v  a2s  . com*/
        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 badge " + "SET logo_id = ? " + "WHERE badge_id = ? ");
            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.rimudb.C3P0PoolTests.java

@Test
public void testConnectionAttributes() throws Exception {
    // Connect to the database
    CompoundDatabase cdb = new CompoundDatabase("/testconfig/pooltests-c3p0-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 ww  .  j  a va 2 s .com*/

    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:org.artifactory.storage.db.util.DbUtils.java

public static void executeSqlStream(Connection con, InputStream in) throws IOException, SQLException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(in, Charsets.UTF_8));
    Statement stmt = con.createStatement();
    try {/*  w  ww .j  a  v a  2s .  co  m*/
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            if (StringUtils.isNotBlank(line) && !line.startsWith("--") && !line.startsWith("#")) {
                sb.append(line);
                if (line.endsWith(";")) {
                    String query = sb.substring(0, sb.length() - 1);
                    if (query.startsWith(INSERT_INTO)) {
                        String databaseProductName = con.getMetaData().getDatabaseProductName();
                        if ("Oracle".equals(databaseProductName)) {
                            query = transformInsertIntoForOracle(query);
                        }
                    }
                    log.debug("Executing query:\n{}", query);
                    try {
                        stmt.executeUpdate(query);
                        if (!con.getAutoCommit()) {
                            con.commit();
                        }
                    } catch (SQLException e) {
                        log.error("Failed to execute query: {}:\n{}", e.getMessage(), query);
                        throw e;
                    }
                    sb = new StringBuilder();
                } else {
                    sb.append("\n");
                }
            }
        }
    } finally {
        IOUtils.closeQuietly(reader);
        close(stmt);
    }
}