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.pinterest.deployservice.db.DBUtilDAOImpl.java

@Override
public Connection getLock(String id) {
    Connection connection = null;
    try {/*w  w w  .j  a v  a2s .com*/
        connection = dataSource.getConnection();
        connection.setAutoCommit(false);
        long status = new QueryRunner().query(connection, String.format(GET_LOCK_TEMPLATE, id, LOCK_TIMEOUT),
                SingleResultSetHandlerFactory.<Long>newObjectHandler());
        if (status == 1L) {
            return connection;
        }
    } catch (Exception e) {
        LOG.error("Failed to call getLock on id {}.", id, e);
    }
    DbUtils.closeQuietly(connection);
    return null;
}

From source file:com.github.lsiu.experiment.eclipselink.TestEclipseLinkEvents.java

@BeforeClass
public void setupDb() throws Exception {
    log.debug("create RESTAURANT_HIST table");
    String sql = IOUtils.toString(this.getClass().getResourceAsStream("/sql/create-history-table.sql"));

    Connection conn = ds.getConnection();
    try {//from   w ww .  j  ava 2s .  co  m
        conn.setAutoCommit(true);
        Statement stmt = conn.createStatement();
        stmt.execute(sql);
    } finally {
        conn.close();
    }

    String testDataDir = "test-data";
    String testFileName = "restaurntData_20130401_233444_700_UTF-8_subset.xml";
    String testFile = "/" + testDataDir + "/" + testFileName;

    log.debug("Prepare database with test file: {}", testFile);
    importer.importData(this.getClass().getResourceAsStream(testFile));
}

From source file:com.china317.gmmp.gmmp_report_analysis.App.java

private static void FatigueRecordsStoreIntoDB(Map<String, FatigueAlarmEntity> map, ApplicationContext context) {
    /**/*from   w  w w. ja v  a  2s.c  o  m*/
     * INSERT INTO TAB_GPSEVENT_FATIGUE SELECT
     * LICENCE,'',ALARMSTARTTIME,ALARMENDTIME,'' FROM ALARMFATIGUE_REA
     */
    Connection conn = null;
    String sql = "";
    try {
        log.info("--------store Fatigue");
        SqlMapClient sc = (SqlMapClient) context.getBean("sqlMapClientDgm");
        conn = sc.getDataSource().getConnection();
        conn.setAutoCommit(false);
        Statement st = conn.createStatement();
        Iterator<String> it = map.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            FatigueAlarmEntity pos = map.get(key);
            sql = "insert into TAB_GPSEVENT_FATIGUE "
                    + " (license,license_color,start_time,end_time,pointcount) " + " values (" + "'"
                    + pos.getLicence() + "'," + "'" + pos.getLicenceColor() + "'," + "'"
                    + pos.getAlarmStartTime() + "'," + "'" + pos.getAlarmEndTime() + "'," + "'"
                    + pos.getPointCount() + "')";
            log.info(sql);
            st.addBatch(sql);
        }
        st.executeBatch();
        conn.commit();
        log.info("[insertIntoDB FatigueAlarmEntity success!!!]");
    } catch (Exception e) {
        log.info(e);
        log.error(sql);
    } finally {
        DgmAnalysisImp.getInstance().getFatigueMap().clear();
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:net.bull.javamelody.SpringTestFacadeImpl.java

/**
 * {@inheritDoc}/*from   ww  w.  ja v a 2  s .co m*/
 */
@Override
public Date nowWithSql() throws SQLException {
    //      final javax.sql.DataSource dataSource = (javax.sql.DataSource) new javax.naming.InitialContext()
    //            .lookup("java:comp/env/jdbc/TestDB");
    final ApplicationContext context = new ClassPathXmlApplicationContext(
            new String[] { "net/bull/javamelody/monitoring-spring.xml", "spring-context.xml", });
    final javax.sql.DataSource dataSource = (javax.sql.DataSource) context.getBean("dataSource");
    final java.sql.Connection connection = dataSource.getConnection();
    connection.setAutoCommit(false);
    try {
        // test pour explain plan en oracle
        //         final PreparedStatement statement = connection
        //               .prepareStatement("select * from v$session where user# = ?");
        final Statement statement = connection.createStatement();
        try {
            //            statement.setInt(1, 36);
            //            statement.executeQuery();

            statement.execute(
                    "DROP ALIAS if exists SLEEP; CREATE ALIAS SLEEP FOR \"java.lang.Thread.sleep(long)\"");
            statement.execute("call sleep(.01)");
            for (int i = 0; i < 5; i++) {
                statement.execute("call sleep(.02)");
            }
        } finally {
            statement.close();
        }
    } finally {
        connection.rollback();
        connection.close();
    }

    return new Date();
}

From source file:azkaban.db.DatabaseSetup.java

private void createTables(final Set<String> tables) throws SQLException, IOException {
    final Connection conn = this.dataSource.getConnection();
    conn.setAutoCommit(false);
    try {//  www .j a  v a  2 s. c om
        for (final String table : tables) {
            runTableScripts(conn, table);
        }
    } finally {
        conn.close();
    }
}

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

public void parserXML() {

    try {//w ww .j ava  2s.c  o m

        //variables BD
        String sql = "INSERT INTO artista VALUES (?,?,?)";
        PreparedStatement preparedStatement;
        Connection connection = dataSource.getConnection();
        connection.setAutoCommit(false);

        //se obtiene elemento raiz
        Element artistas = this.xmlDocumento.getRootElement();
        //elementos 2do nivel
        List<Element> listaArtistas = artistas.getChildren();
        Iterator<Element> i = listaArtistas.iterator();

        while (i.hasNext()) {
            Element artista = i.next();

            //Elementos de tercer nivel
            Attribute id = artista.getAttribute("id");
            Element nombre = artista.getChild("nombre");
            Element descripcion = artista.getChild("descripcion");

            //construye parametros de la query
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1, id.getIntValue());
            preparedStatement.setString(2, nombre.getText());
            preparedStatement.setString(3, descripcion.getText());

            preparedStatement.execute();
        }

        //preparedStatement = connection.prepareStatement(sql);           
        // preparedStatement.setInt(1, valor);
        //  preparedStatement.execute();

        connection.commit();
    } catch (Exception e) {
        //*** se quit el return porque el mtodo es void
        System.out.println(e.getMessage());
    }

}

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

public void parserXML() {

    try {/*from   w  w  w  .  j  av  a 2  s.  c o m*/

        //variables BD
        String sql = "INSERT INTO estado VALUES (?,?)";
        String sqlM = "INSERT INTO municipio VALUES (?,?,?)";
        PreparedStatement preparedStatement;
        Connection connection = dataSource.getConnection();
        connection.setAutoCommit(false);

        //se obtiene elemento raiz
        Element estado = this.xmlDocumento.getRootElement();
        //elementos 2do nivel
        Element nombre = estado.getChild("nombre");
        Element municipios = estado.getChild("municipios");
        Attribute id = estado.getAttribute("id");
        //construye parametros de la query
        preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1, id.getIntValue());
        preparedStatement.setString(2, nombre.getText());
        preparedStatement.execute();

        List<Element> listaMunicipios = municipios.getChildren("municipio");
        Iterator<Element> i = listaMunicipios.iterator();

        while (i.hasNext()) {
            Element municipio = i.next();
            //Elementos de tercer nivel
            Attribute idMunicipio = municipio.getAttribute("id");
            String nombreMunicipio = municipio.getText();
            //construye parametros de la query
            preparedStatement = connection.prepareStatement(sqlM);
            preparedStatement.setInt(1, idMunicipio.getIntValue());
            preparedStatement.setString(2, nombreMunicipio);
            preparedStatement.setInt(3, id.getIntValue());

            preparedStatement.execute();
        }

        connection.commit();
    } catch (Exception e) {
        //*** se quit el return porque el mtodo es void
        System.out.println(e.getMessage());
    }

}

From source file:net.firejack.platform.model.upgrader.operator.AbstractOperator.java

/**
 * Executor method which execute sql commands
 *
 * @param type - operator class//  w w  w. jav a  2s . c om
 */
public void execute(T type) {
    try {
        Connection connection = dataSource.getConnection();
        try {
            connection.setAutoCommit(true);
            PreparedStatement statement = null;
            try {
                String[] sqlCommands = sqlCommands(type);
                for (String sqlCommand : sqlCommands) {
                    logger.info("Execute sql: \n" + sqlCommand);
                    statement = connection.prepareStatement(sqlCommand);
                    statement.executeUpdate();
                }
            } finally {
                JdbcUtils.closeStatement(statement);
            }
        } finally {
            connection.setAutoCommit(false);
            JdbcUtils.closeConnection(connection);
        }
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}

From source file:dk.netarkivet.common.utils.DBUtils.java

/**
 * Method to perform a rollback of complex DB updates.  If no commit has
 * been performed, this will undo the entire transaction, otherwise
 * nothing will happen. If autoCommit is true then no action is taken.
 * This method should be called in a finally block with
 * no DB updates after the last commit.//from w w  w. jav a 2 s.c o m
 * Thus exceptions while closing are ignored, but logged as warnings.
 *
 * NB: the provided connection is not closed.
 *
 * @param c the db-connection
 * @param action The action going on, before calling this method
 * @param o The Object being acted upon by this action
 */
public static void rollbackIfNeeded(Connection c, String action, Object o) {
    ArgumentNotValid.checkNotNull(c, "Connection c");
    try {
        if (!c.getAutoCommit()) {
            c.rollback();
            c.setAutoCommit(true);
        }
    } catch (SQLException e) {
        log.warn("SQL error doing rollback after " + action + " " + o + "\n"
                + ExceptionUtils.getSQLExceptionCause(e), e);
        // Can't throw here, we want the real exception
    }
}

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

@Override
protected Connection getConnection() {
    try {/*from   w ww .  j  av a 2s .c  o  m*/
        Connection conn = dbConf.getConnection();
        conn.setAutoCommit(false);
        PreparedStatement stmt = conn.prepareStatement("SET extra_float_digits TO 0");
        stmt.executeUpdate();
        conn.commit();
        return conn;
    } catch (SQLException sqlE) {
        LOG.error("Could not get connection to test server: " + sqlE);
        return null;
    } catch (ClassNotFoundException cnfE) {
        LOG.error("Could not find driver class: " + cnfE);
        return null;
    }
}