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.splicemachine.derby.test.framework.SpliceRoleWatcher.java

@Override
protected void starting(Description description) {
    LOG.trace("Starting");
    executeDrop(roleName.toUpperCase());
    Connection connection = null;
    Statement statement = null;//from w w w.  ja va2  s . com
    ResultSet rs = null;
    try {
        connection = SpliceNetConnection.getConnection();
        statement = connection.createStatement();
        statement.execute(String.format("create role %s", roleName));
        connection.commit();
    } catch (Exception e) {
        LOG.error("Role statement is invalid ");
        e.printStackTrace();
        throw new RuntimeException(e);
    } finally {
        DbUtils.closeQuietly(rs);
        DbUtils.closeQuietly(statement);
        DbUtils.commitAndCloseQuietly(connection);
    }
    super.starting(description);
}

From source file:azkaban.db.DatabaseOperatorImpl.java

/**
 * transaction method Implementation./*  www  .  j  a v a 2  s  .  com*/
 *
 */
@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:com.krawler.esp.servlets.FileImporterServlet.java

public static void mapImportedRes(String resmapval, HashMap mp) throws ServiceException {
    Connection conn = null;
    try {/*from w w w. jav  a 2  s  . com*/
        conn = DbPool.getConnection();
        com.krawler.utils.json.base.JSONArray jsonArray = new com.krawler.utils.json.base.JSONArray(resmapval);
        com.krawler.utils.json.base.JSONObject jobj = new com.krawler.utils.json.base.JSONObject();
        for (int k = 0; k < jsonArray.length(); k++) {
            jobj = jsonArray.getJSONObject(k);
            if (jobj.getString("resourceid").length() > 0 && mp.containsKey(jobj.getString("tempid"))) {
                ArrayList taskids = (ArrayList) mp.get(jobj.getString("tempid"));
                String tasks = taskids.toString();
                tasks = tasks.substring(1, tasks.lastIndexOf("]"));
                projdb.insertimportedtaskResources(conn, tasks, jobj.getString("resourceid"));
            }
        }
        conn.commit();
    } catch (JSONException ex) {
        DbPool.quietRollback(conn);
    } catch (ServiceException ex) {
        DbPool.quietRollback(conn);
    } catch (Exception ex) {
        DbPool.quietRollback(conn);
    } finally {
        DbPool.quietClose(conn);
    }
}

From source file:iudex.da.ContentUpdater.java

public void update(List<UniMap> references) throws SQLException {
    Connection conn = dataSource().getConnection();
    try {//www  . j  a v 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:hermes.store.schema.DefaultJDBCAdapter.java

public void recreateDatabase(Connection connection) throws SQLException {
    executeStatements(connection, statements.getDeleteDatabaseStatements());

    connection.commit();

    createDatabase(connection);/*ww  w  .j a v  a2 s.c o m*/
}

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

/**
 * Recupera la fecha de pago o cobro de cada una de las facturas cuyo tipo se envia por parametro
 * @param billType tipo de factura//from   w  w w  .j  a va 2s  .  co  m
 */
public static Date[] getFechaFacturaOriginal(String billType) throws Exception {
    Connection con = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    LineNumberReader file = null;
    Date[] result = new Date[0];

    try {
        log.info("RECOVERING FECHAS " + 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 vacia
        String sql = "SELECT date_add(creationDate, INTERVAL expiration DAY) as date FROM Bill B where billType = ? order by date";
        pstmt = con.prepareStatement(sql);
        pstmt.setString(1, billType);
        rs = pstmt.executeQuery();

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

        while (rs.next()) {
            result[counter] = rs.getDate(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:com.moss.blankslate.PostgresqlCatalogFactory.java

public BlankslateCatalogHandle createCatalog(boolean deleteOnExit) throws Exception {
    checkConfig();/*from  www  .  j a  v a 2 s.c o  m*/

    String testCatalogName = "test-" + sequenceNum + "-" + getCatalogNameQualifier();

    synchronized (sequenceNum) {
        sequenceNum++;
    }

    JdbcConnectionConfig config = new JdbcConnectionConfig(DatabaseType.DB_TYPE_POSTGRESQL, null, hostname,
            null, "postgres", LOGIN, password);

    Connection adminConnection = config.createConnection();

    if (catalogExists(testCatalogName, adminConnection)) {
        log.warn("Database '" + testCatalogName + "' already exists... will be deleted");
        deleteCatalog(testCatalogName);
    }

    // THIS IS THE CONFIGURATION FOR THE AS-YET-UNCREATED CATALOG
    JdbcConnectionConfig newCatalogConfig = new JdbcConnectionConfig(DatabaseType.DB_TYPE_POSTGRESQL, null,
            hostname, null, testCatalogName, LOGIN, password);

    // CREATE THE CATALOG
    adminConnection.createStatement().execute("CREATE DATABASE \"" + testCatalogName + "\" TEMPLATE template0");
    adminConnection.close();
    assertClosed(adminConnection);

    // CREATE THE DEFAULT SCHEMA
    Connection newDatabaseConnection = newCatalogConfig.createConnection();
    dropSchema(DEFAULT_SCHEMA_NAME, newDatabaseConnection);
    newDatabaseConnection.createStatement().execute("create schema " + DEFAULT_SCHEMA_NAME + "");
    newDatabaseConnection.commit();
    newDatabaseConnection.close();
    assertClosed(newDatabaseConnection);

    BlankslateCatalogHandle handle = new BlankslateCatalogHandle(testCatalogName, newCatalogConfig,
            DEFAULT_SCHEMA_NAME);
    return handle;
}

From source file:com.splicemachine.derby.test.framework.SpliceGrantWatcher.java

@Override
protected void starting(Description description) {
    LOG.trace("Starting");
    Connection connection = null;
    Statement statement = null;//from   w  w  w  .java 2s  .com
    ResultSet rs = null;
    try {
        connection = userName == null ? SpliceNetConnection.getConnection()
                : SpliceNetConnection.getConnectionAs(userName, password);
        statement = connection.createStatement();
        statement.execute(createString);
        connection.commit();
    } catch (Exception e) {
        LOG.error("Grant statement is invalid ");
        e.printStackTrace();
        throw new RuntimeException(e);
    } finally {
        DbUtils.closeQuietly(rs);
        DbUtils.closeQuietly(statement);
        DbUtils.commitAndCloseQuietly(connection);
    }
    super.starting(description);
}

From source file:net.firejack.platform.core.utils.db.DBUtils.java

private static void insertDataToTargetTable(TablesMapping mapping, Connection sourceConnection,
        Connection targetConnection) throws SQLException {
    Map<Column, Column> columnMapping = mapping.getColumnMapping();
    if (columnMapping.isEmpty()) {
        logger.warn("No columns are detected - no data to insert.");
    } else {/*from   ww w  .  jav a 2s . c om*/
        ResultSet rs = selectDataFromSource(sourceConnection, mapping);

        String insertQuery = populateInsertQuery(mapping);
        PreparedStatement insertStatement = targetConnection.prepareStatement(insertQuery);
        targetConnection.setAutoCommit(false);
        try {
            int currentStep = 1;
            while (rs.next()) {
                for (int i = 1; i <= columnMapping.size(); i++) {
                    insertStatement.setObject(i, rs.getObject(i));
                }
                insertStatement.addBatch();
                if (++currentStep > DEFAULT_BATCH_SIZE) {
                    insertStatement.executeBatch();
                    targetConnection.commit();
                    currentStep = 1;
                }
            }
            if (currentStep != 1) {
                insertStatement.executeBatch();
                targetConnection.commit();
            }
        } catch (SQLException e) {
            logger.error(e.getMessage(), e);
            targetConnection.rollback();
        } finally {
            insertStatement.close();
            rs.close();
        }
    }
}

From source file:com.cyclopsgroup.tornado.hibernate.impl.DefaultHibernateService.java

/**
 * Overwrite or implement method commitTransaction()
 *
 * @see com.cyclopsgroup.tornado.hibernate.HibernateService#commitTransaction(java.lang.String)
 *//*from  w  w w . ja v  a 2 s.  co  m*/
public void commitTransaction(String dataSourceName) throws Exception {
    SessionWrapper wrapper = (SessionWrapper) localSession.get();
    if (wrapper != null) {
        Session session = wrapper.getSession(dataSourceName);
        if (session != null) {
            session.flush();
        }
        Transaction transaction = wrapper.getTransaction(dataSourceName);
        if (transaction != null) {
            transaction.commit();
        }
        Connection dbcon = wrapper.getConnection(dataSourceName);
        dbcon.commit();
    }
}