Example usage for java.sql Connection setAutoCommit

List of usage examples for java.sql Connection setAutoCommit

Introduction

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

Prototype

void setAutoCommit(boolean autoCommit) throws SQLException;

Source Link

Document

Sets this connection's auto-commit mode to the given state.

Usage

From source file:com.cloudera.sqoop.manager.MySQLAuthTest.java

private void dropTimestampTables() throws SQLException {
    SqoopOptions options = new SqoopOptions(AUTH_CONNECT_STRING, null);
    options.setUsername(AUTH_TEST_USER);
    options.setPassword(AUTH_TEST_PASS);

    manager = new DirectMySQLManager(options);

    Connection connection = null;
    Statement st = null;//  ww w.j av a2 s . c  o m

    connection = manager.getConnection();
    connection.setAutoCommit(false);
    st = connection.createStatement();

    try {
        st.executeUpdate("DROP TABLE IF EXISTS mysqlTimestampTable0");
        st.executeUpdate("DROP TABLE IF EXISTS mysqlTimestampTable1");
        st.executeUpdate("DROP TABLE IF EXISTS mysqlTimestampTable2");
        st.executeUpdate("DROP TABLE IF EXISTS mysqlTimestampTable3");
        st.executeUpdate("DROP TABLE IF EXISTS mysqlTimestampTable4");
        st.executeUpdate("DROP TABLE IF EXISTS mysqlTimestampTable5");
        connection.commit();
    } finally {
        st.close();
        connection.close();
    }
}

From source file:io.apiman.gateway.engine.jdbc.JdbcRegistry.java

/**
 * @see io.apiman.gateway.engine.IRegistry#registerClient(io.apiman.gateway.engine.beans.Client, io.apiman.gateway.engine.async.IAsyncResultHandler)
 *//*w w w  . j a  v a2  s .  c  o  m*/
@Override
public void registerClient(Client client, IAsyncResultHandler<Void> handler) {
    Connection conn = null;
    try {
        conn = ds.getConnection();
        conn.setAutoCommit(false);
        QueryRunner run = new QueryRunner();

        // Validate the client and populate the api map with apis found during validation.
        validateClient(client, conn);

        // Remove any old data first, then (re)insert
        run.update(conn, "DELETE FROM gw_clients WHERE org_id = ? AND id = ? AND version = ?", //$NON-NLS-1$
                client.getOrganizationId(), client.getClientId(), client.getVersion());

        String bean = mapper.writeValueAsString(client);
        run.update(conn, "INSERT INTO gw_clients (api_key, org_id, id, version, bean) VALUES (?, ?, ?, ?, ?)", //$NON-NLS-1$
                client.getApiKey(), client.getOrganizationId(), client.getClientId(), client.getVersion(),
                bean);

        DbUtils.commitAndClose(conn);
        handler.handle(AsyncResultImpl.create((Void) null));
    } catch (Exception re) {
        DbUtils.rollbackAndCloseQuietly(conn);
        handler.handle(AsyncResultImpl.create(re, Void.class));
    }
}

From source file:egovframework.rte.fdl.logging.db.EgovJDBCAppender.java

/**
 * connection ?        ?? override ./*from   w  w  w.j a v a2  s .co  m*/
 * 
 * @param sql
 *            - log4j.xml ? ? <param name="sql" .. ? 
 * @exception SQLException
 */
@Override
protected void execute(String sql) throws SQLException {

    Connection con = null;
    Statement stmt = null;

    try {
        con = getConnection();
        // dataSource bean ?  autoCommit false  ?   true  
        con.setAutoCommit(true);

        stmt = con.createStatement();
        stmt.executeUpdate(sql);
    } catch (SQLException e) {
        e.printStackTrace();
        throw e;
    } finally {
        stmt.close();
        closeConnection(con);
    }

    // LogFactory.getLog("sysoutLogger").debug("Execute: " + sql);
}

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  a2 s .  c  o  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:cz.cas.lib.proarc.common.user.UserManagerSql.java

@Override
public List<Group> findUserGroups(int userId) {
    try {/* w  w  w .j a  v  a  2 s  .c  om*/
        Connection c = getConnection();
        try {
            c.setAutoCommit(true);
            return groupStorage.findUserGroups(c, userId);
        } finally {
            DbUtils.close(c);
        }
    } catch (SQLException ex) {
        throw new IllegalStateException(ex);
    }
}

From source file:cz.cas.lib.proarc.common.user.UserManagerSql.java

@Override
public Set<Permission> findUserPermissions(int userId) {
    try {//from   ww w. j  ava 2  s  . c o  m
        Connection c = getConnection();
        try {
            c.setAutoCommit(true);
            return permissionStorage.find(c, userId);
        } finally {
            DbUtils.close(c);
        }
    } catch (SQLException ex) {
        throw new IllegalStateException(ex);
    }
}

From source file:edu.caltechUcla.sselCassel.projects.jMarkets.server.data.DBConnector.java

/** Start a database transaction */
public void startTransaction(Connection conn) {
    try {//from ww  w .  j  a  v a2  s .com
        conn.setAutoCommit(false);
    } catch (Exception e) {
        log.error("Failed to set database to auto-commit false mode", e);
    }
}

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 {//from w ww.  j av  a 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 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:com.its.core.local.hezhou.task.ExportImageFilesReadTaskNew.java

@Override
public void execute() {

    long startTime = System.currentTimeMillis();
    Connection conn = null;

    try {/*from www.  j  a va 2 s.c  o m*/
        conn = ConnectionProviderFactory.getInstance().getConnectionProvider().getConnection();
        conn.setAutoCommit(false);

        List<VehicelRecordBean> recordList = this.getExportRecordList(conn);
        int size = recordList.size();
        log.debug("" + size + "");
        if (size == 0)
            return;

        short currentExcelRow = 1;
        for (int i = 0; i < size; i++) {
            VehicelRecordBean record = (VehicelRecordBean) recordList.get(i);

            //
            this.updateRecordStatus(conn, record.getId());

            String filePath = this.getImgSaveDir() + "/" + DEVICE_MAP.get(record.getDeviceIp()) + "/"
                    + DateHelper.dateToString(record.getCatchTime(), "yyyyMMdd") + "/"
                    + DateHelper.dateToString(record.getCatchTime(), "HH") + "/";
            FileHelper.createDir(filePath);

            StringBuffer fileNameBuffer = new StringBuffer("X03");

            fileNameBuffer.append("R").append(DEVICE_MAP.get(record.getDeviceIp())).append("D")
                    .append(DIRECTION_MAP.get(record.getDirectionCode())).append("L")
                    .append(record.getDrivewayNo()).append("I").append("000").append("V").append("000")
                    .append("N").append((int) (Math.random() * (99999 - 10000)) + 10000).append("T")
                    .append(DateHelper.dateToString(record.getCatchTime(), "yyyyMMddHHmmssSSS"));
            if (StringHelper.isNotEmpty(record.getPlate()) && !record.getPlate().equals("")) {
                fileNameBuffer.append("&").append(record.getPlate()).append("&")
                        .append(COLOR_MAP.get(record.getPlateColorCode()));
            }
            fileNameBuffer.append("S11.JPG");

            String fileName = fileNameBuffer.toString();

            filePath += fileName;
            log.info("" + this.getHttpPrefix() + record.getFeatureImagePath());
            byte[] imageByte = ImageHelper.getImageBytes(this.getHttpPrefix() + record.getFeatureImagePath());
            log.info("" + filePath);
            FileHelper.writeFile(imageByte, filePath);

            conn.commit();
            currentExcelRow++;
        }
        long currentTime = System.currentTimeMillis();
        log.info("" + (currentExcelRow - 1) + " " + ((currentTime - startTime) / 1000F)
                + "");
    } catch (Exception ex) {
        log.error("" + ex.getMessage(), ex);
        try {
            conn.commit();
        } catch (Exception e) {
        }
    } finally {
        if (conn != null) {
            try {
                ConnectionProviderFactory.getInstance().getConnectionProvider().closeConnection(conn);
            } catch (Exception ex2) {
            }
        }
    }

}

From source file:mx.com.pixup.portal.dao.FormaPagoDaoJdbc.java

@Override
public FormaPago insertFormaPago(FormaPago formaPago) {
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;//from  www.j  av a 2  s  .  co  m

    String sql = "insert into forma_pago (descripcion) values (?)";

    try {
        connection = dataSource.getConnection();

        connection.setAutoCommit(false);

        preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
        preparedStatement.setString(1, formaPago.getDescripcion());

        preparedStatement.execute();

        connection.commit();
        resultSet = preparedStatement.getGeneratedKeys();

        resultSet.next();
        formaPago.setId(resultSet.getInt(1));

        return formaPago;
    } catch (Exception e) {

    } finally {
        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (Exception e) {
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception e) {
            }
        }

    }
    return null;
}