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:azkaban.database.AbstractJdbcLoader.java

protected Connection getDBConnection(boolean autoCommit) throws IOException {
    Connection connection = null;
    try {//from   w ww.  j  ava 2 s .c  o m
        connection = dataSource.getConnection();
        connection.setAutoCommit(autoCommit);
    } catch (Exception e) {
        DbUtils.closeQuietly(connection);
        throw new IOException("Error getting DB connection.", e);
    }

    return connection;
}

From source file:com.vecna.dbDiff.builder.RelationalDatabaseBuilderTest.java

private RelationalDatabase getDatabase() throws Exception {
    try (MetadataFactory factory = new ThreadLocalMetadataFactory("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1", "sa",
            "")) {
        try (InputStream stream = getClass().getResourceAsStream("/test-db.sql")) {
            String sql = IOUtils.toString(stream);

            Connection ddlConnection = factory.getMetadata().getConnection();
            ddlConnection.setAutoCommit(true);

            for (String sqlStatement : sql.split(";")) {
                ddlConnection.createStatement().execute(sqlStatement);
            }//from   www . j  a  va  2  s. com
        }

        RelationalDatabaseBuilder builder = new RelationalDatabaseBuilderImpl(factory);
        return builder.createRelationalDatabase(new CatalogSchema(null, "PUBLIC"));
    }
}

From source file:be.ugent.tiwi.sleroux.newsrec.stormNewsFetch.dao.mysqlImpl.JDBCRatingsDao.java

/**
 *
 * @throws RatingsDaoException/*from w  w w  .ja  v  a  2 s . c  om*/
 */
public JDBCRatingsDao() throws RatingsDaoException {
    logger.debug("constructor called");
    if (connectionPool == null) {
        try {
            logger.debug("creating connectionpool");
            String driver = bundle.getString("dbDriver");
            String user = bundle.getString("dbUser");
            String pass = bundle.getString("dbPass");
            String url = bundle.getString("dbUrl");
            url = url + "?user=" + user + "&password=" + pass;
            connectionPool = new BasicDataSource();
            connectionPool.setDriverClassName(driver);
            connectionPool.setUsername(user);
            connectionPool.setPassword(pass);
            connectionPool.setUrl(url);

            logger.debug("connectionpool created");

            logger.debug("creating preparedstatements");
            String statementText = bundle.getString("selectRatingsQuery");
            Connection conn = connectionPool.getConnection();
            conn.setAutoCommit(true);
            selectStatement = conn.prepareStatement(statementText);
            statementText = bundle.getString("insertUpdateRatingsQuery");
            insertUpdateRatingStatement = conn.prepareStatement(statementText);
            logger.debug("created preparedstatements");
        } catch (SQLException ex) {
            logger.error(ex.getMessage(), ex);
            throw new RatingsDaoException(ex);
        }
    }
}

From source file:gobblin.data.management.retention.sql.SqlBasedRetentionPoc.java

/**
 * <ul>/*from ww w.j  a va  2  s.  c  o m*/
 * <li>Create the in-memory database and connect
 * <li>Create tables for snapshots and daily_paritions
 * <li>Attach all user defined functions from {@link SqlUdfs}
 * </ul>
 *
 */
@BeforeClass
public void setup() throws SQLException {
    basicDataSource = new BasicDataSource();
    basicDataSource.setDriverClassName("org.apache.derby.jdbc.EmbeddedDriver");
    basicDataSource.setUrl("jdbc:derby:memory:derbypoc;create=true");

    Connection connection = basicDataSource.getConnection();
    connection.setAutoCommit(false);
    this.connection = connection;

    execute("CREATE TABLE Snapshots (dataset_path VARCHAR(255), name VARCHAR(255), path VARCHAR(255), ts TIMESTAMP, row_count bigint)");
    execute("CREATE TABLE Daily_Partitions (dataset_path VARCHAR(255), path VARCHAR(255), ts TIMESTAMP)");

    // Register UDFs
    execute("CREATE FUNCTION TIMESTAMP_DIFF(timestamp1 TIMESTAMP, timestamp2 TIMESTAMP, unitString VARCHAR(50)) RETURNS BIGINT PARAMETER STYLE JAVA NO SQL LANGUAGE JAVA EXTERNAL NAME 'gobblin.data.management.retention.sql.SqlUdfs.timestamp_diff'");
}

From source file:com.healthcit.cacure.utils.DBSchemaUpdater.java

@Override
public void afterPropertiesSet() throws Exception {
    Connection connection = DataSourceUtils.getConnection(dataSource);
    connection.setAutoCommit(false);
    try {/*from  w w w  .  j av a2s . co m*/
        Statement statement = connection.createStatement();
        try {
            long version = 0;
            try {
                ResultSet rs = statement.executeQuery("select schema_version from sys_variables limit 1;");
                try {
                    if (!rs.next()) {
                        throw new RuntimeException("Seems there is no any row in sys_variables table.");
                    }
                    version = rs.getLong(1);
                } finally {
                    rs.close();
                }
            } catch (PSQLException e) {
                //               it's needed for executing more scripts successfully
                connection.rollback();
                log.info("Can't find sys_variables tables. Appling initial script.");
                String initialScriptStatements = getStatementsFor(0);
                if (initialScriptStatements == null) {
                    throw new RuntimeException("Can't find initial script.");
                }
                statement.executeUpdate(initialScriptStatements);
                //there is already schema_version at 0
                connection.commit();
                log.info("Initial script succesfully executed.");
            }
            for (long v = version + 1;; v++) {
                String statements = getStatementsFor(v);
                if (statements == null) {
                    break;
                }
                log.info("Updating schema to " + v + " version...");
                statement.execute(statements);
                statement.executeUpdate("update sys_variables set schema_version = " + v + ";");
                connection.commit();
                log.info("OK");
            }
        } catch (BatchUpdateException e) {
            if (e.getNextException() != null) {
                e.getNextException().printStackTrace();
            }
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            connection.rollback();
        } finally {
            statement.close();
        }
    } finally {
        DataSourceUtils.releaseConnection(connection, dataSource);
    }
}

From source file:mayoapp.migrations.V0400_2024__move_order_items_to_own_table.java

@Override
public void migrate(Connection connection) throws Exception {
    connection.setAutoCommit(false);

    Statement queryStatement = connection.createStatement();
    ResultSet data = queryStatement.executeQuery("SELECT * from purchase_order");

    List<Order> orders = Lists.newArrayList();
    List<OrderItem> orderItems = Lists.newArrayList();

    ObjectMapper mapper = new ObjectMapper();

    while (data.next()) {
        Order order = new Order();
        order.setId((UUID) data.getObject("entity_id"));

        String orderDataString = data.getString("order_data");
        Map<String, Object> orderData = mapper.readValue(orderDataString,
                new TypeReference<Map<String, Object>>() {
                });//w w  w  .j a  v a 2 s.c om

        List<Map<String, Object>> items = (List<Map<String, Object>>) orderData.get("items");

        for (Map<String, Object> item : items) {
            OrderItem orderItem = new OrderItem();

            orderItem.setId(UUID.randomUUID());
            orderItem.setOrderId(order.getId());

            if (item.containsKey("id") && String.class.isAssignableFrom(item.get("id").getClass())) {
                orderItem.setPurchasableId(UUID.fromString((String) item.get("id")));
            }
            orderItem.setType((String) item.get("type"));
            orderItem.setTitle((String) item.get("title"));
            orderItem.setQuantity(((Integer) item.get("quantity")).longValue());
            orderItem.setUnitPrice(BigDecimal.valueOf((Double) item.get("unitPrice")));
            orderItem.setItemTotal(BigDecimal.valueOf((Double) item.get("itemTotal")));
            if (item.containsKey("vatRate")) {
                orderItem.setVatRate(BigDecimal.valueOf((Double) item.get("vatRate")));
            }

            if (item.containsKey("addons")) {
                orderItem.addData("addons", convertAddonsToMap((List<Map<String, Object>>) item.get("addons")));
            }

            orderItems.add(orderItem);
        }

        orderData.remove("items");
        order.setOrderData(orderData);
        orders.add(order);
    }

    queryStatement.close();

    // 1. Update orders

    PreparedStatement updateOrders = connection
            .prepareStatement("UPDATE purchase_order SET order_data = CAST (? AS json) WHERE entity_id =?");

    for (Order order : orders) {
        updateOrders.setObject(1, mapper.writeValueAsString(order.getOrderData()));
        updateOrders.setObject(2, order.getId());
        updateOrders.addBatch();
    }

    updateOrders.executeBatch();

    // 2. Insert items

    PreparedStatement insertItems = connection.prepareStatement(
            "INSERT INTO purchase_order_item (id, order_id, purchasable_id, type, title, quantity, unit_price, "
                    + "item_total, vat_rate, data) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, CAST (? as json))");

    for (OrderItem item : orderItems) {
        insertItems.setObject(1, item.getId());
        insertItems.setObject(2, item.getOrderId());
        insertItems.setObject(3, item.getPurchasableId());
        insertItems.setString(4, item.getType());
        insertItems.setString(5, item.getTitle());
        insertItems.setLong(6, item.getQuantity());
        insertItems.setBigDecimal(7, item.getUnitPrice());
        insertItems.setBigDecimal(8, item.getItemTotal());
        insertItems.setBigDecimal(9, item.getVatRate());
        insertItems.setString(10, mapper.writeValueAsString(item.getData()));
        insertItems.addBatch();
    }

    insertItems.executeBatch();
}

From source file:gridool.db.sql.ParallelSQLExecJob.java

private static void runPreparation(@Nonnull final DBAccessor dba, @Nonnull final String mapQuery,
        @Nonnull final GridNode[] masters, @Nonnull final GridNode localNode,
        @Nonnull final ReadWriteLock rwlock, @Nonnull final String outputName) throws GridException {
    final String prepareQuery = constructTaskResultTablesDDL(mapQuery, masters, localNode, outputName);
    final Connection conn;
    try {/*from w  w w.j  a va2  s.co  m*/
        conn = dba.getPrimaryDbConnection();
        conn.setAutoCommit(false);
    } catch (SQLException e) {
        LOG.error("An error caused in the preparation phase", e);
        throw new GridException(e);
    }
    final Lock wlock = rwlock.writeLock();
    try {
        wlock.lock();
        JDBCUtils.update(conn, prepareQuery);
        conn.commit();
    } catch (SQLException e) {
        LOG.error("An error caused in the preparation phase", e);
        try {
            conn.rollback();
        } catch (SQLException sqle) {
            LOG.warn("Failed to rollback", sqle);
        }
        throw new GridException(e);
    } finally {
        wlock.unlock();
        JDBCUtils.closeQuietly(conn);
    }
}

From source file:org.alfresco.hibernate.DialectFactoryBean.java

@SuppressWarnings("deprecation")
@Override/*from   w w w  .  ja  v  a2s  .  c o m*/
public Dialect getObject() throws SQLException {
    Session session = ((SessionFactory) this.localSessionFactory.getObject()).openSession();
    Configuration cfg = this.localSessionFactory.getConfiguration();
    Connection con = null;
    try {
        // make sure that we AUTO-COMMIT
        con = session.connection();
        con.setAutoCommit(true);
        DatabaseMetaData meta = con.getMetaData();
        Dialect dialect = DialectFactory.buildDialect(cfg.getProperties(), meta.getDatabaseProductName(),
                meta.getDatabaseMajorVersion());
        dialect = changeDialect(cfg, dialect);
        return dialect;
    } finally {
        try {
            con.close();
        } catch (Exception e) {
        }
    }
}

From source file:iudex.da.ContentUpdater.java

public void update(List<UniMap> references) throws SQLException {
    Connection conn = dataSource().getConnection();
    try {/*  ww  w  .  j av a2  s .  c o m*/
        conn.setAutoCommit(false);
        conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);

        update(references, conn);

        conn.commit();
    } finally {
        if (conn != null)
            conn.close();
    }
}

From source file:com.che.software.testato.domain.dao.jdbc.impl.PrioritizationDAO.java

/**
 * Creates the prioritization related to the given hierarchy.
 * /*  w ww . j a  v a  2  s  .c o m*/
 * @author Clement HELIOU (clement.heliou@che-software.com).
 * @param hierarchyId the given hierarchy id.
 * @since July, 2011.
 * @throws PrioritizationCreationDAOException if an error occurs during the
 *         creation.
 */
@Override
public void createHierarchyPrioritization(int hierarchyId) throws PrioritizationCreationDAOException {
    LOGGER.debug("createHierarchyPrioritization(" + hierarchyId + ").");
    Connection connection = null;
    try {
        connection = getDataSource().getConnection();
        connection.setAutoCommit(false);
        getQueryRunner().update(connection,
                "INSERT INTO prioritization(prioritization_id) VALUES(nextval('prioritization_seq')) ");
        Integer createdPrioritization = (Integer) getQueryRunner().query(connection,
                "SELECT MAX(prioritization_id)::int AS prioritizationId FROM prioritization ",
                new ScalarHandler("prioritizationId"));
        getQueryRunner().update(connection,
                "INSERT INTO hierarchy_prioritization(hierarchy_id, prioritization_id) VALUES(?,?) ",
                new Object[] { hierarchyId, createdPrioritization });
        connection.commit();
    } catch (SQLException e) {
        try {
            connection.rollback();
        } catch (SQLException e1) {
            throw new PrioritizationCreationDAOException(e);
        }
        throw new PrioritizationCreationDAOException(e);
    } finally {
        if (null != connection) {
            DbUtils.closeQuietly(connection);
        }
    }
}