Example usage for java.sql Connection commit

List of usage examples for java.sql Connection commit

Introduction

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

Prototype

void commit() throws SQLException;

Source Link

Document

Makes all changes made since the previous commit/rollback permanent and releases any database locks currently held by this Connection object.

Usage

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

private static void LybcOverSpeedRecordsStoreIntoDB(Map<String, PtmOverSpeed> overSpeedRecords,
        ApplicationContext context) {//from w  ww.  j  a v  a 2s  .c o  m
    // INSERT INTO
    // TAB_ALARM_OVERSPEED(LICENCE,BEGIN_TIME,END_TIME,SPEED,IS_END,AREA,MAX_SPEED)
    // SELECT LICENSE,BEGINTIME,ENDTIME,AVGSPEED,'1',FLAG,MAXSPEED FROM
    // ALARMOVERSPEED_REA WHERE BUSINESSTYPE = '3'
    String sql = "";

    Connection conn = null;
    try {
        SqlMapClient sc = (SqlMapClient) context.getBean("sqlMapClientLybc");
        conn = sc.getDataSource().getConnection();
        conn.setAutoCommit(false);
        Statement st = conn.createStatement();
        Iterator<String> it = overSpeedRecords.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            PtmOverSpeed pos = overSpeedRecords.get(key);
            sql = "insert into TAB_ALARM_OVERSPEED "
                    + " (LICENCE,BEGIN_TIME,END_TIME,SPEED,IS_END,AREA,MAX_SPEED) " + " values ('"
                    + pos.getLicense() + "','" + pos.getBeginTime() + "','" + pos.getEndTIme() + "',"
                    + pos.getAvgSpeed() + "," + "1" + "," + pos.getFlag() + "," + pos.getMaxSpeed() + ")";
            log.info(sql);
            st.addBatch(sql);
        }
        st.executeBatch();
        conn.commit();
        log.info("[insertIntoDB OverSpeed success!!!]");
    } catch (Exception e) {
        e.printStackTrace();
        log.error(sql);
    } finally {
        overSpeedRecords.clear();
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}

From source file:org.killbill.bus.TestPersistentBusDemo.java

@Test(groups = "slow")
public void testDemo() throws SQLException, PersistentBus.EventBusException {

    // Create a Handler (with @Subscribe method)
    final DummyHandler handler = new DummyHandler();
    bus.register(handler);// w  w  w .  j  a  v a  2s .c o  m

    // Extract connection from dataSource
    final Connection connection = dataSource.getConnection();
    final DummyEvent event = new DummyEvent("foo", 1L, 2L, UUID.randomUUID());

    PreparedStatement stmt = null;
    try {
        // In one transaction we both insert a dummy value in some table, and post the event (using same connection/transaction)
        connection.setAutoCommit(false);
        stmt = connection.prepareStatement("insert into dummy (dkey, dvalue) values (?, ?)");
        stmt.setString(1, "Great!");
        stmt.setLong(2, 47L);
        stmt.executeUpdate();
        bus.postFromTransaction(event, connection);
        connection.commit();
    } finally {
        if (stmt != null) {
            stmt.close();
        }
        if (connection != null) {
            connection.close();
        }
    }

    //
    // Verify we see the dummy value inserted and also received the event posted
    //
    final Connection connection2 = dataSource.getConnection();
    PreparedStatement stmt2 = null;
    try {
        stmt2 = connection2.prepareStatement("select * from dummy where dkey = ?");
        stmt2.setString(1, "Great!");
        final ResultSet rs2 = stmt2.executeQuery();
        int found = 0;
        while (rs2.next()) {
            found++;
        }
        Assert.assertEquals(found, 1);
    } finally {
        stmt2.close();
    }
    if (connection2 != null) {
        connection2.close();
    }

    Assert.assertTrue(handler.waitForCompletion(1, 3000));
}

From source file:dqyt.cy6.yutao.common.port.adapter.persistence.eventsourcing.mysql.MySQLJDBCEventStore.java

public List<DispatchableDomainEvent> eventsSince(long aLastReceivedEvent) {

    Connection connection = this.connection();

    ResultSet result = null;//  w w w . j  a  v a2 s . co m

    try {
        PreparedStatement statement = connection
                .prepareStatement("SELECT event_id, event_body, event_type FROM tbl_es_event_store "
                        + "WHERE event_id > ? " + "ORDER BY event_id");

        statement.setLong(1, aLastReceivedEvent);

        result = statement.executeQuery();

        List<DispatchableDomainEvent> sequence = this.buildEventSequence(result);

        connection.commit();

        return sequence;

    } catch (Throwable t) {
        throw new EventStoreException(
                "Cannot query event for sequence since: " + aLastReceivedEvent + " because: " + t.getMessage(),
                t);
    } finally {
        if (result != null) {
            try {
                result.close();
            } catch (SQLException e) {
                // ignore
            }
        }
        try {
            connection.close();
        } catch (SQLException e) {
            // ignore
        }
    }
}

From source file:com.alfaariss.oa.engine.user.provisioning.storage.internal.jdbc.JDBCInternalStorage.java

/**
 * Updates the user in the internal storage 
 * @see IInternalStorage#update(ProvisioningUser)
 *//* w w w. j  a va 2  s. c om*/
public void update(ProvisioningUser user) throws UserException {
    Connection oConnection = null;
    try {
        oConnection = _oDataSource.getConnection();
        oConnection.setAutoCommit(false);

        updateProfile(oConnection, user);

        oConnection.commit();
    } catch (UserException e) {
        rollback(oConnection);
        throw e;
    } catch (Exception e) {
        rollback(oConnection);
        _logger.fatal("Could not update user", e);
        throw new UserException(SystemErrors.ERROR_INTERNAL);
    } finally {
        try {
            if (oConnection != null)
                oConnection.close();
        } catch (Exception e) {
            _logger.error("Could not close connection", e);
        }
    }
}

From source file:com.saasovation.common.port.adapter.persistence.eventsourcing.mysql.MySQLJDBCEventStore.java

@Override
public List<DispatchableDomainEvent> eventsSince(long aLastReceivedEvent) {

    Connection connection = this.connection();

    ResultSet result = null;//from  w  w w  .j a va 2 s . co  m

    try {
        PreparedStatement statement = connection
                .prepareStatement("SELECT event_id, event_body, event_type FROM tbl_es_event_store "
                        + "WHERE event_id > ? " + "ORDER BY event_id");

        statement.setLong(1, aLastReceivedEvent);

        result = statement.executeQuery();

        List<DispatchableDomainEvent> sequence = this.buildEventSequence(result);

        connection.commit();

        return sequence;

    } catch (Throwable t) {
        throw new EventStoreException(
                "Cannot query event for sequence since: " + aLastReceivedEvent + " because: " + t.getMessage(),
                t);
    } finally {
        if (result != null) {
            try {
                result.close();
            } catch (SQLException e) {
                // ignore
            }
        }
        try {
            connection.close();
        } catch (SQLException e) {
            // ignore
        }
    }
}

From source file:net.gcolin.simplerepo.search.SearchController.java

public void rebuild() throws IOException {
    if (running) {
        return;//ww w. j av  a 2 s .  com
    }
    running = true;
    configManager.setCurrentAction(REBUILD + "initialize");
    nb = 0;
    try {
        final QueryRunner run = new QueryRunner();

        try {
            Connection connection = null;
            try {
                connection = datasource.getConnection();
                connection.setAutoCommit(false);
                run.update(connection, "delete from artifacttype");
                run.update(connection, "delete from artifactversion");
                run.update(connection, "delete from artifact");
                run.update(connection, "update artifactindex set artifact=1,version=1");
                connection.commit();
            } catch (SQLException ex) {
                connection.rollback();
                throw ex;
            } finally {
                DbUtils.close(connection);
            }
        } catch (SQLException ex) {
            logger.log(Level.SEVERE, null, ex);
            throw new IOException(ex);
        }
        for (final Repository repository : configManager.getConfiguration().getRepositories()) {
            File repo = new File(configManager.getRoot(), repository.getName());
            if (repo.exists()) {
                Files.walkFileTree(repo.toPath(), new SimpleFileVisitor<Path>() {
                    @Override
                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                        nb++;
                        if (nb % 20 == 0) {
                            configManager.setCurrentAction(REBUILD + " " + nb + " files");
                        }
                        if (file.toString().endsWith(".pom")) {
                            Model model = readPom(file.toFile());
                            add(repository, file.toFile(), model);
                        }
                        return FileVisitResult.CONTINUE;
                    }

                });
            }
        }
    } finally {
        running = false;
        configManager.setCurrentAction(null);
    }
}

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

/**
 * Update an item to refine it.// w  w w  . jav a 2s.c o m
 * 
 * @author Clement HELIOU (clement.heliou@che-software.com).
 * @param itemId the item id.
 * @return the created action plan id.
 * @since July, 2011.
 * @throws ItemUpdateDAOException if an error occurs during the update.
 */
@Override
public int refineItem(int itemId) throws ItemUpdateDAOException {
    LOGGER.debug("refineItem(" + itemId + ").");
    Connection connection = null;
    try {
        connection = getDataSource().getConnection();
        connection.setAutoCommit(false);
        getQueryRunner().update(connection,
                "INSERT INTO action_plan(action_plan_id) VALUES(nextval('action_plan_seq')) ");
        Integer createdActionPlan = (Integer) getQueryRunner().query(connection,
                "SELECT MAX(action_plan_id)::int AS actionPlanId FROM action_plan ",
                new ScalarHandler("actionPlanId"));
        getQueryRunner().update(connection, "UPDATE item SET action_plan_id = ? WHERE item_id = ? ",
                new Object[] { createdActionPlan, itemId });
        connection.commit();
        return createdActionPlan;
    } catch (SQLException e) {
        try {
            connection.rollback();
        } catch (SQLException e1) {
            throw new ItemUpdateDAOException(e1);
        }
        throw new ItemUpdateDAOException(e);
    } finally {
        if (null != connection) {
            DbUtils.closeQuietly(connection);
        }
    }
}

From source file:dk.netarkivet.archive.arcrepositoryadmin.ReplicaCacheHelpers.java

/**
 * Method for updating the checksum status of a replicafileinfo instance.
 * Updates the following fields for the entry in the replicafileinfo:
 * <br/> checksum_status = OK.// w  w  w  .j  av a2 s  .com
 * <br/> upload_status = UPLOAD_COMLPETE.
 * <br/> checksum_checkdatetime = current time.
 * <br/><br/>
 * The file is required to exist in the replica.
 *
 * @param replicafileinfoId The id of the replicafileinfo.
 * @param con An open connection to the archive database
 */
protected static void updateReplicaFileInfoChecksumOk(long replicafileinfoId, Connection con) {
    PreparedStatement statement = null;
    try {
        // The SQL statement
        final String sql = "UPDATE replicafileinfo SET checksum_status = ?, "
                + "checksum_checkdatetime = ?, upload_status = ? " + "WHERE replicafileinfo_guid = ?";
        Date now = new Date(Calendar.getInstance().getTimeInMillis());

        // complete the SQL statement.
        statement = DBUtils.prepareStatement(con, sql, ChecksumStatus.OK.ordinal(), now,
                ReplicaStoreState.UPLOAD_COMPLETED.ordinal(), replicafileinfoId);

        // execute the SQL statement
        statement.executeUpdate();
        con.commit();
    } catch (Exception e) {
        String msg = "Problems updating the replicafileinfo.";
        log.warn(msg);
        throw new IOFailure(msg, e);
    } finally {
        DBUtils.closeStatementIfOpen(statement);
    }
}

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

private static void DgmOverSpeedRecordsStoreIntoDB(Map<String, PtmOverSpeed> overSpeedRecords,
        ApplicationContext context) {//  ww  w .j a  v a 2 s  .c  o m
    // INSERT INTO
    // TAB_GPSEVENT_OVERSPEED(VID,TYPE,,BEGIN_TIME,END_TIME,DETAIL,AREA,MAX_SPEED,MIN_SPEED)
    // SELECT CODE,'overspeed',BEGINTIME,ENDTIME,AVGSPEED,FLAG,MAXSPEED,''
    // FROM ALARMOVERSPEED_REA WHERE BUSINESSTYPE = '1'

    String sql = "";
    Connection conn = null;
    try {
        SqlMapClient sc = (SqlMapClient) context.getBean("sqlMapClientDgm");
        conn = sc.getDataSource().getConnection();
        conn.setAutoCommit(false);
        Statement st = conn.createStatement();
        Iterator<String> it = overSpeedRecords.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            PtmOverSpeed pos = overSpeedRecords.get(key);
            sql = "INSERT INTO TAB_GPSEVENT_OVERSPEED (VID,TYPE,BEGIN_TIME,END_TIME,DETAIL,AREA,MAX_SPEED,MIN_SPEED) "
                    + " values ('" + pos.getCode() + "','" + "overspeed" + "','" + pos.getBeginTime() + "','"
                    + pos.getEndTIme() + "'," + pos.getAvgSpeed() + "," + pos.getFlag() + ","
                    + pos.getMaxSpeed() + "," + 0 + ")";
            log.info(sql);
            st.addBatch(sql);
        }
        st.executeBatch();
        conn.commit();
        log.info("[insertIntoDB OverSpeed success!!!]");
    } catch (Exception e) {
        e.printStackTrace();
        log.error(sql);
    } finally {
        overSpeedRecords.clear();
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}

From source file:dk.netarkivet.archive.arcrepositoryadmin.ReplicaCacheHelpers.java

/**
 * Method for updating the filelist of a replicafileinfo instance.
 * Updates the following fields for the entry in the replicafileinfo:
 * <br/> filelist_status = missing.
 * <br/> filelist_checkdatetime = current time.
 *
 * The replicafileinfo is in the filelist.
 *
 * @param replicafileinfoId The id of the replicafileinfo.
 * @param con An open connection to the archive database
 *///w  w  w .j av  a  2s .c  om
protected static void updateReplicaFileInfoMissingFromFilelist(long replicafileinfoId, Connection con) {
    PreparedStatement statement = null;
    try {
        // The SQL statement
        final String sql = "UPDATE replicafileinfo SET filelist_status = ?, "
                + "filelist_checkdatetime = ?, upload_status = ? " + "WHERE replicafileinfo_guid = ?";

        Date now = new Date(Calendar.getInstance().getTimeInMillis());

        // complete the SQL statement.
        statement = DBUtils.prepareStatement(con, sql, FileListStatus.MISSING.ordinal(), now,
                ReplicaStoreState.UPLOAD_FAILED.ordinal(), replicafileinfoId);

        // execute the SQL statement
        statement.executeUpdate();
        con.commit();
    } catch (Exception e) {
        String msg = "Problems updating the replicafileinfo.";
        log.warn(msg);
        throw new IOFailure(msg, e);
    } finally {
        DBUtils.closeStatementIfOpen(statement);
    }
}