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:dk.netarkivet.archive.arcrepositoryadmin.ReplicaCacheHelpers.java

/**
 * Method for updating the filelist_updated field for a given replica
 * in the replica table./*  w  ww  .jav a 2s  .com*/
 * This is called when a filelist_job or a checksum_job has been handled.
 *
 * The following fields for the entry in the replica table:
 * <br/> filelist_updated = now.
 *
 * @param rep The replica which has just been updated.
 * @param connection An open connection to the archive database
 */
protected static void updateFilelistDateForReplica(Replica rep, Connection connection) {
    PreparedStatement statement = null;
    try {
        Date now = new Date(Calendar.getInstance().getTimeInMillis());
        final String sql = "UPDATE replica SET filelist_updated = ? WHERE " + "replica_id = ?";
        statement = DBUtils.prepareStatement(connection, sql, now, rep.getId());
        statement.executeUpdate();
        connection.commit();
    } catch (Exception e) {
        String msg = "Cannot update the filelist_updated for replica '" + rep + "'.";
        log.warn(msg);
        throw new IOFailure(msg, e);
    } finally {
        DBUtils.closeStatementIfOpen(statement);
    }
}

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

public void appendWith(EventStreamId aStartingIdentity, List<DomainEvent> anEvents) {

    // tbl_es_event_store must have a composite primary key
    // consisting of {stream_name}:{streamVersion} so that
    // appending a stale version will fail the pk constraint

    Connection connection = this.connection();

    try {//from  w ww .  ja  va  2  s.c o m
        int index = 0;

        for (DomainEvent event : anEvents) {
            this.appendEventStore(connection, aStartingIdentity, index++, event);
        }

        connection.commit();

        this.notifyDispatchableEvents();

    } catch (Throwable t1) {
        try {
            this.connection().rollback();
        } catch (Throwable t2) {
            // ignore
        }

        throw new EventStoreAppendException("Could not append to event store because: " + t1.getMessage(), t1);
    } finally {
        try {
            connection.close();
        } catch (SQLException e) {
            // ignore
        }
    }
}

From source file:azkaban.trigger.JdbcTriggerLoader.java

private synchronized void addTrigger(Connection connection, Trigger t, EncodingType encType)
        throws TriggerLoaderException {

    QueryRunner runner = new QueryRunner();

    long id;//from   ww w .  jav a 2s.  c  om

    try {
        runner.update(connection, ADD_TRIGGER, DateTime.now().getMillis());
        connection.commit();
        id = runner.query(connection, LastInsertID.LAST_INSERT_ID, new LastInsertID());

        if (id == -1L) {
            logger.error("trigger id is not properly created.");
            throw new TriggerLoaderException("trigger id is not properly created.");
        }

        t.setTriggerId((int) id);
        updateTrigger(t);
        logger.info("uploaded trigger " + t.getDescription());
    } catch (SQLException e) {
        throw new TriggerLoaderException("Error creating trigger.", e);
    }

}

From source file:com.autentia.tnt.bill.migration.support.OriginalInformationRecoverer.java

/**
 * Recupera la suma total de todos los conceptos de cada una de las facturas cuyo tipo se envia por parametro
 * @param billType tipo de factura//from  w ww  . j  ava  2 s  .  c o  m
 */
public static double[] getImporteFacturaOriginal(String billType) throws Exception {
    Connection con = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    LineNumberReader file = null;
    double[] result = new double[0];

    try {
        log.info("RECOVERING IMPORTE FACTURAS " + billType + " ORIGINALES");

        // connect to database
        Class.forName(BillToBillPaymentMigration.DATABASE_DRIVER);
        con = DriverManager.getConnection(BillToBillPaymentMigration.DATABASE_CONNECTION,
                BillToBillPaymentMigration.DATABASE_USER, BillToBillPaymentMigration.DATABASE_PASS); //NOSONAR
        con.setAutoCommit(false); //DATABASE_PASS vacio.            

        String sql = "SELECT sum((bb.units*bb.amount)*(1+(bb.iva/100))) as total from Bill b left join BillBreakDown bb on b.id=bb.billId, Organization o, Project p where b.projectId = p.id and p.organizationId = o.id and b.billType= ? group by b.id order by total";

        pstmt = con.prepareStatement(sql);

        rs = pstmt.executeQuery();
        pstmt.setString(1, billType);

        rs.last();
        result = new double[rs.getRow()];
        rs.beforeFirst();
        int counter = 0;

        while (rs.next()) {
            result[counter] = rs.getDouble(1);
            log.info("\t" + result[counter]);
            counter++;
        }
        con.commit();
    } catch (Exception e) {
        log.error("FAILED: WILL BE ROLLED BACK: ", e);
        if (con != null) {
            con.rollback();
        }
    } finally {
        cierraFichero(file);
        liberaConexion(con, pstmt, rs);
    }
    return result;
}

From source file:eionet.cr.dao.virtuoso.VirtuosoSpoBinaryDAO.java

@Override
public void delete(List<String> subjectUris) throws DAOException {

    // make sure the list is not null or empty
    if (subjectUris == null || subjectUris.isEmpty()) {
        return;//from  www.  j a  va  2 s  . com
    }

    // convert URIs to hashes
    ArrayList<Long> hashes = new ArrayList<Long>();
    for (String uri : subjectUris) {
        hashes.add(Long.valueOf(Hashes.spoHash(uri)));
    }

    // prepare connection and the hashes comma-separated
    Connection conn = null;
    String hashesStr = "(" + Util.toCSV(hashes) + ")";

    try {
        // do it in a transaction
        conn = getSQLConnection();
        conn.setAutoCommit(false);

        // delete references from SPO_BINARY
        SQLUtil.executeUpdate("delete from SPO_BINARY where SUBJECT in " + hashesStr, conn);

        // commit the transaction
        conn.commit();
    } catch (SQLException e) {
        throw new DAOException(e.getMessage(), e);
    } finally {
        SQLUtil.rollback(conn);
        SQLUtil.close(conn);
    }
}

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

@Override
public void appendWith(EventStreamId aStartingIdentity, List<DomainEvent> anEvents) {

    // tbl_es_event_store must have a composite primary key
    // consisting of {stream_name}:{streamVersion} so that
    // appending a stale version will fail the pk constraint

    Connection connection = this.connection();

    try {/*from   w w w .jav a  2s.  com*/
        int index = 0;

        for (DomainEvent event : anEvents) {
            this.appendEventStore(connection, aStartingIdentity, index++, event);
        }

        connection.commit();

        this.notifyDispatchableEvents();

    } catch (Throwable t1) {
        try {
            this.connection().rollback();
        } catch (Throwable t2) {
            // ignore
        }

        throw new EventStoreAppendException("Could not append to event store because: " + t1.getMessage(), t1);
    } finally {
        try {
            connection.close();
        } catch (SQLException e) {
            // ignore
        }
    }
}

From source file:net.riezebos.thoth.configuration.persistence.ThothDB.java

protected void initializeSchema(Connection connection) throws SQLException, DDLException, IOException {
    DatabaseIdiom idiom = DatabaseIdiomFactory.getDatabaseIdiom(connection);
    DDLExecuter executer = new DDLExecuter(connection, idiom);
    boolean tableExists = executer.tableExists("thoth_users", getConfiguration().getDatabaseUser());
    if (!tableExists) {
        executer.execute(CREATE_SCRIPT);
        connection.commit();
    }//from  w ww. ja v a2s  .  c  om

    performUpgrades(connection);
}

From source file:org.cfr.capsicum.datasource.CayenneTransactionManager.java

@Override
protected void doCommit(DefaultTransactionStatus status) {
    CayenneTransactionObject txObject = (CayenneTransactionObject) status.getTransaction();
    Connection con = txObject.getConnectionHolder().getConnection();
    if (status.isDebug()) {
        logger.debug("Committing JDBC transaction on Connection [" + con + "]");
    }//  ww w. j  a va2 s.  c o  m
    try {
        status.flush();
        con.commit();
    } catch (SQLException ex) {
        throw new TransactionSystemException("Could not commit JDBC transaction",
                exceptionTranslator.convertJdbcAccessException(ex));
    } catch (CayenneRuntimeException ex) {
        throw new TransactionSystemException("Could not commit JDBC transaction",
                exceptionTranslator.convertAccessException(ex));
    }
}

From source file:com.cloudera.sqoop.testutil.HsqldbTestServer.java

/**
 * Create a table./* w  w w . j  a  v  a  2s. co  m*/
 */
public void createSchema() throws SQLException {

    Connection connection = null;
    Statement st = null;

    try {
        connection = getConnection();

        st = connection.createStatement();
        st.executeUpdate("DROP TABLE " + DUMMY_TABLE_NAME + " IF EXISTS");
        st.executeUpdate("CREATE TABLE " + DUMMY_TABLE_NAME + "(intField1 INT, intField2 INT)");

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

        if (null != connection) {
            connection.close();
        }
    }
}

From source file:dk.netarkivet.harvester.datamodel.extendedfield.ExtendedFieldValueDBDAO.java

@Override
public void delete(long aExtendedfieldValueID) throws IOFailure {
    ArgumentNotValid.checkNotNull(aExtendedfieldValueID, "aExtendedfieldValueID");

    Connection c = HarvestDBConnection.get();
    PreparedStatement stm = null;
    try {// w  w w . jav  a2s .co m
        c.setAutoCommit(false);

        stm = c.prepareStatement("DELETE FROM extendedfieldvalue " + "WHERE extendedfieldvalue_id = ?");
        stm.setLong(1, aExtendedfieldValueID);
        stm.executeUpdate();

        c.commit();

    } catch (SQLException e) {
        String message = "SQL error deleting extendedfieldvalue for ID " + aExtendedfieldValueID + "\n"
                + ExceptionUtils.getSQLExceptionCause(e);
        log.warn(message, e);
    } finally {
        DBUtils.closeStatementIfOpen(stm);
        DBUtils.rollbackIfNeeded(c, "delete extendedfield value", aExtendedfieldValueID);
        HarvestDBConnection.release(c);
    }

}