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.interface21.jdbc.datasource.DriverManagerDataSource.java

public Connection getConnection(String username, String password) throws SQLException {
    logger.info("Creating new JDBC connection: " + this.url);
    Connection con = getConnectionFromDriverManager(this.url, username, password);
    con.setAutoCommit(true);
    return con;/*  w w w  . j av a  2s  .co m*/
}

From source file:kr.co.bitnine.octopus.testutils.MemoryDatabase.java

public void importJSON(Class<?> clazz, String resourceName) throws Exception {
    Connection conn = getConnection();
    conn.setAutoCommit(false);
    Statement stmt = conn.createStatement();

    JSONParser jsonParser = new JSONParser();
    JSONArray tables = (JSONArray) jsonParser
            .parse(new InputStreamReader(clazz.getResourceAsStream(resourceName)));
    for (Object tableObj : tables) {
        StringBuilder queryBuilder = new StringBuilder();

        JSONObject table = (JSONObject) tableObj;

        String tableName = jsonValueToSqlIdent(table.get("table-name"));
        queryBuilder.append("CREATE TABLE ").append(tableName).append('(');
        JSONArray schema = (JSONArray) table.get("table-schema");
        for (Object columnNameObj : schema) {
            String columnName = jsonValueToSqlValue(columnNameObj);
            queryBuilder.append(columnName).append(',');
        }/*w  ww . jav  a  2  s.co m*/
        queryBuilder.setCharAt(queryBuilder.length() - 1, ')');
        stmt.execute(queryBuilder.toString());

        JSONArray rows = (JSONArray) table.get("table-rows");
        for (Object rowObj : rows) {
            JSONArray row = (JSONArray) rowObj;

            queryBuilder.setLength(0);
            queryBuilder.append("INSERT INTO ").append(tableName).append(" VALUES(");
            for (Object columnObj : row)
                queryBuilder.append(jsonValueToSqlValue(columnObj)).append(',');
            queryBuilder.setCharAt(queryBuilder.length() - 1, ')');
            stmt.executeUpdate(queryBuilder.toString());
        }
    }

    stmt.close();
    conn.commit();
    conn.close();
}

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

public void parserXML() {

    try {//from   www.j av  a2  s .  com

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

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

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

            Attribute id = disco.getAttribute("id");
            Attribute idioma = disco.getAttribute("idioma");
            Attribute pais = disco.getAttribute("pais");
            Attribute disquera = disco.getAttribute("disquera");
            Attribute genero = disco.getAttribute("genero");

            //Elementos de 3er nivel
            Element titulo = disco.getChild("titulo");
            Element fechalanzamiento = disco.getChild("fechalanzamiento");
            Element precio = disco.getChild("precio");
            Element cantidad = disco.getChild("cantidad");
            Element promocion = disco.getChild("promocion");
            Element iva = disco.getChild("iva");

            //construye parametros de la query
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1, id.getIntValue());
            preparedStatement.setString(2, titulo.getText());
            preparedStatement.setString(3, fechalanzamiento.getText());
            preparedStatement.setDouble(4, Double.parseDouble(precio.getText()));
            preparedStatement.setInt(5, Integer.parseInt(cantidad.getText()));
            preparedStatement.setInt(6, idioma.getIntValue());
            preparedStatement.setInt(7, pais.getIntValue());
            preparedStatement.setInt(8, disquera.getIntValue());
            preparedStatement.setInt(9, genero.getIntValue());
            preparedStatement.setInt(10, Integer.parseInt(promocion.getText()));
            preparedStatement.setInt(11, Integer.parseInt(iva.getText()));

            preparedStatement.execute();
        }

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

}

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

/** Update a database by executing all the statements in
 *  the updates String array.//w  w w  .  java  2 s .  c  o m
 *  NOTE: this must NOT be used for tables under version control
 *  It must only be used in connection with temporary tables e.g. used
 *  for backup.
 *
 *  NB: the method does not close the provided connection.
 *
 * @param connection connection to the database.
 * @param updates The SQL statements that makes the necessary
 * updates.
 * @throws IOFailure in case of problems in interacting with the database
 */
public static void executeSQL(Connection connection, final String... updates) {
    ArgumentNotValid.checkNotNull(updates, "String... updates");
    PreparedStatement st = null;
    String s = "";

    try {
        connection.setAutoCommit(false);
        for (String update : updates) {
            s = update;
            log.debug("Executing SQL-statement: " + update);
            st = prepareStatement(connection, update);
            st.executeUpdate();
            st.close();
        }
        connection.setAutoCommit(true);
        log.debug("Updated database using updates '" + StringUtils.conjoin(";", updates) + "'.");
    } catch (SQLException e) {
        String msg = "SQL error updating database with sql: " + s + "\n"
                + ExceptionUtils.getSQLExceptionCause(e);
        log.warn(msg, e);
        throw new IOFailure(msg, e);
    } finally {
        rollbackIfNeeded(connection, "updating table with SQL: ", StringUtils.conjoin(";", updates) + "'.");
    }
}

From source file:org.openvpms.tools.data.migration.DetailsMigrator.java

/**
 * Export the details.//w  w  w  .  j a v  a 2  s  .co  m
 *
 * @throws SQLException for any SQL error
 */
public void export() throws SQLException {
    Connection connection = dataSource.getConnection();
    connection.setAutoCommit(false);
    try {
        export(connection, "acts", "act_details", "act_id");
        export(connection, "act_relationships", "act_relationship_details", "act_relationship_id");
        export(connection, "contacts", "contact_details", "contact_id");
        export(connection, "documents", "document_details", "document_id");
        export(connection, "entities", "entity_details", "entity_id");
        export(connection, "entity_identities", "entity_identity_details", "entity_identity_id");
        export(connection, "entity_relationships", "entity_relationship_details", "entity_relationship_id");
        export(connection, "lookups", "lookup_details", "lookup_id");
        export(connection, "lookup_relationships", "lookup_relationship_details", "lookup_relationship_id");
        export(connection, "participations", "participation_details", "participation_id");
        export(connection, "product_prices", "product_price_details", "product_price_id");
    } finally {
        connection.close();
    }
}

From source file:azkaban.db.DatabaseOperatorImpl.java

/**
 * transaction method Implementation.//from  www .  jav a  2  s. c  o m
 *
 */
@Override
public <T> T transaction(SQLTransaction<T> operations) throws SQLException {
    Connection conn = null;
    try {
        conn = queryRunner.getDataSource().getConnection();
        conn.setAutoCommit(false);
        DatabaseTransOperator transOperator = new DatabaseTransOperatorImpl(queryRunner, conn);
        T res = operations.execute(transOperator);
        conn.commit();
        return res;
    } catch (SQLException ex) {
        // todo kunkun-tang: Retry logics should be implemented here.
        logger.error("transaction failed", ex);
        throw ex;
    } finally {
        DbUtils.closeQuietly(conn);
    }
}

From source file:net.noday.core.dao.AppDao.java

public App getAppConfig() {
    List<String> tables = jdbc.queryForList("show tables", String.class);
    Connection conn = DataSourceUtils.getConnection(jdbc.getDataSource());
    try {//w  w w.  jav  a 2  s. c  o m
        conn.setAutoCommit(false);
        if (tables == null || tables.size() == 0 || !tables.contains("app_config")) {
            initDB();
        } else {
            String version = jdbc.queryForObject("select a.version from app_config a limit 1", String.class);
            if (!"1.1".equalsIgnoreCase(version)) {
                updateDB("1_1");
            }
        }
        conn.commit();
    } catch (DataAccessException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    String sql = "select * from app_config limit 1";
    App cfg = jdbc.queryForObject(sql, new BeanPropertyRowMapper<App>(App.class));
    if (cfg == null) {
        throw new AppStartupException("??");
    }
    return cfg;
}

From source file:com.consol.citrus.samples.todolist.dao.JdbcTodoListDao.java

@Override
public void deleteByTitle(String title) {
    try {//w  w w.  ja  va 2  s .co  m
        Connection connection = getConnection();
        try {
            connection.setAutoCommit(true);
            PreparedStatement statement = connection
                    .prepareStatement("DELETE FROM todo_entries WHERE title = ?");
            try {
                statement.setString(1, title);
                statement.executeUpdate();
            } finally {
                statement.close();
            }
        } finally {
            connection.close();
        }
    } catch (SQLException e) {
        throw new DataAccessException("Could not delete entries for title " + title, e);
    }
}

From source file:com.consol.citrus.samples.todolist.dao.JdbcTodoListDao.java

@Override
public void save(TodoEntry entry) {
    try {//from   w  w w. j  a  va  2s .  co m
        Connection connection = getConnection();
        try {
            connection.setAutoCommit(true);
            PreparedStatement statement = connection
                    .prepareStatement("INSERT INTO todo_entries (id, title, description) VALUES (?, ?, ?)");
            try {
                statement.setString(1, getNextId());
                statement.setString(2, entry.getTitle());
                statement.setString(3, entry.getDescription());
                statement.executeUpdate();
            } finally {
                statement.close();
            }
        } finally {
            connection.close();
        }
    } catch (SQLException e) {
        throw new DataAccessException("Could not save entry " + entry, e);
    }
}

From source file:org.sakaiproject.genericdao.springutil.SmartDataSourceWrapper.java

/**
 * Fixes up the auto-commit to be equal to the setting for this connection if possible,
 * will not cause an exception though if it fails to do it
 * @param connection the connection//w  w w .  jav  a 2 s.  com
 * @return the same connection that was input
 */
private Connection fixAutoCommit(Connection connection) {
    try {
        if (connection.getAutoCommit() != autoCommitConnection) {
            connection.setAutoCommit(autoCommitConnection);
        }
    } catch (SQLException e) {
        // do nothing
    }
    return connection;
}