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:de.langmi.spring.batch.examples.readers.jdbc.JdbcPagingItemReaderTests.java

/**
 * Setup Datasource and create table for test.
 *
 * @throws Exception //from   ww  w. j  a v a 2  s  .  c  o  m
 */
@Before
public void setUp() throws Exception {
    // DataSource Setup, apache commons 
    dataSource = new BasicDataSource();
    dataSource.setDriverClassName("org.hsqldb.jdbcDriver");
    dataSource.setUrl("jdbc:hsqldb:mem:testdb");
    dataSource.setUsername("sa");
    dataSource.setPassword("");

    // drop table if exists
    Connection conn = dataSource.getConnection();
    Statement st = conn.createStatement();
    st.execute(DROP_TEST_TABLE);
    conn.commit();
    st.close();
    conn.close();

    // create table
    conn = dataSource.getConnection();
    st = conn.createStatement();
    st.execute(CREATE_TEST_TABLE);
    conn.commit();
    st.close();
    conn.close();

    // fill with values
    conn = dataSource.getConnection();
    // prevent auto commit for batching
    conn.setAutoCommit(false);
    PreparedStatement ps = conn.prepareStatement(INSERT);
    // fill with values
    for (int i = 0; i < EXPECTED_COUNT; i++) {
        ps.setString(1, String.valueOf(i));
        ps.addBatch();
    }
    ps.executeBatch();
    conn.commit();
    ps.close();
    conn.close();
}

From source file:de.langmi.spring.batch.examples.readers.support.CompositeCursorItemReaderTest.java

/**
 * Properly tears down a HSQLDB in-memory database.
 *
 * @param dataSource// w w  w.  j a  va  2  s.c  om
 * @throws Exception 
 */
private void tearDownDataSource(final DataSource dataSource) throws Exception {
    Connection conn = dataSource.getConnection();
    Statement st = conn.createStatement();
    st.execute("SHUTDOWN");
    conn.commit();
    st.close();
}

From source file:com.cloudera.sqoop.manager.DirectPostgreSQLExportManualTest.java

@Override
protected Connection getConnection() {
    try {/*from w w w.j  a  va2s  .  co  m*/
        Connection conn = dbConf.getConnection();
        conn.setAutoCommit(false);
        PreparedStatement stmt = conn.prepareStatement("SET extra_float_digits TO 0");
        stmt.executeUpdate();
        conn.commit();
        return conn;
    } catch (SQLException sqlE) {
        LOG.error("Could not get connection to test server: " + sqlE);
        return null;
    } catch (ClassNotFoundException cnfE) {
        LOG.error("Could not find driver class: " + cnfE);
        return null;
    }
}

From source file:com.stratelia.silverpeas.silverstatistics.control.SilverStatisticsService.java

/**
 * @param type/*ww  w . j a v a2 s .co m*/
 * @param data
 */
@Override
public void putStats(StatType type, String data) {
    StrTokenizer stData = new StrTokenizer(data, SEPARATOR);
    List<String> dataArray = stData.getTokenList();
    if (myStatsConfig.isGoodDatas(type, dataArray)) {
        Connection myCon = DBUtil.makeConnection(SILVERSTATISTICS_DATASOURCE);
        try {
            SilverStatisticsDAO.putDataStats(myCon, type, dataArray, myStatsConfig);
            if (!myCon.getAutoCommit()) {
                myCon.commit();
            }
        } catch (SQLException e) {
            SilverTrace.error("silverstatistics", "SilverStatisticsEJB.putStats",
                    "silverstatistics.MSG_ALIMENTATION_BD",
                    "typeOfStats = " + type + ", dataArray = " + dataArray, e);
        } catch (StatisticsRuntimeException e) {
            SilverTrace.error("silverstatistics", "SilverStatisticsEJB.putStats", "MSG_CONNECTION_BD");
        } finally {
            DBUtil.close(myCon);
        }

    } else {
        SilverTrace.error("silverstatistics", "SilverStatisticsEJB.putStats", "MSG_CONFIG_DATAS",
                "data en entree=" + data + " pour " + type);
    }
}

From source file:com.viettel.logistic.wms.service.SerialInventoryServiceImpl.java

private void commit(Session session, Transaction transaction, Connection con) {
    try {/* ww w  .  j ava 2 s.  c  om*/
        if (transaction != null) {
            transaction.commit();
        }
        if (con != null) {
            con.commit();
        }
        if (session != null && session.isOpen()) {
            session.close();
        }

        if (con != null && !con.isClosed()) {
            con.close();
        }
    } catch (SQLException ex) {
        Logger.getLogger(StockImportServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.migratebird.database.impl.DefaultSQLHandler.java

/**
 * Ends a transaction that was started using startTransaction
 * by committing and turning auto commit back on.
 *
 * @param dataSource The data source, not null
 *///  ww  w  .  j a  va2s  . c om
public void endTransactionAndCommit(DataSource dataSource) {
    Connection connection = getConnection(dataSource);
    try {
        connection.commit();

    } catch (Exception e) {
        try {
            connection.rollback();
        } catch (Exception t) {
            logger.warn("Unable to perform database rollback after commit failure.");
        }
        throw new DatabaseException("Error while performing database commit.", e);
    } finally {
        reenableAutoCommit(connection);
    }
}

From source file:de.langmi.spring.batch.examples.readers.support.CompositeCursorItemReaderTest.java

/**
 * Create a table and fill with some test data.
 *
 * @param dataSource/*from w  w w . ja v  a 2  s .co  m*/
 * @throws Exception 
 */
private void createTableWithTestData(final DataSource dataSource) throws Exception {
    // create table
    Connection conn = dataSource.getConnection();
    Statement st = conn.createStatement();
    st.execute(CREATE_TEST_TABLE);
    conn.commit();
    st.close();
    conn.close();

    // fill with values
    conn = dataSource.getConnection();
    // prevent auto commit for batching
    conn.setAutoCommit(false);
    PreparedStatement ps = conn.prepareStatement(INSERT);
    // fill with values
    for (int i = 0; i < EXPECTED_COUNT; i++) {
        ps.setString(1, String.valueOf(i));
        ps.addBatch();
    }
    ps.executeBatch();
    conn.commit();
    ps.close();
    conn.close();
}

From source file:net.lshift.diffa.dbapp.OracleTestSchema.java

@Override
public void create() throws SQLException {
    BoneCPConfig config = new BoneCPConfig();
    config.setJdbcUrl(System.getProperty("jdbcUrl"));
    config.setUsername(adminUsername);/*w  w w.jav  a 2 s  .  c  om*/
    config.setPassword(adminPassword);

    BoneCPDataSource ds = new BoneCPDataSource(config);
    ds.setDriverClass(System.getProperty("jdbcDriverClass"));

    Connection connection = ds.getConnection();
    Factory factory = new Factory(connection, dialect());
    factory.execute(String.format("create user %s identified by %s", dbUsername(), dbPassword()));
    factory.execute(String.format("grant dba to %s", dbUsername()));
    connection.commit();
    connection.close();
    ds.close();
}

From source file:name.marcelomorales.siqisiqi.bonecp.DataSourceProviderTest.java

@Test
public void testStatistics() throws Exception {
    Config config = ConfigFactory.parseString("bonecp.url=\"jdbc:derby:memory:dbstats;create=true\"")
            .withFallback(ConfigFactory.load());

    DataSourceProvider dsp = new DataSourceProvider(config);

    assertNull(dsp.getStatistics());/* w ww .ja  va  2s .c  om*/

    DataSource dataSource = dsp.get();

    Connection connection = dataSource.getConnection();

    connection.createStatement().execute("CREATE TABLE TABLETEST1 (ACOLUMN VARCHAR(10))");
    connection.commit();

    QueryRunner queryRunner = new QueryRunner();
    queryRunner.update(connection, "INSERT INTO TABLETEST1 VALUES ('AAA')");
    queryRunner.update(connection, "INSERT INTO TABLETEST1 VALUES (?)", "BBB");
    queryRunner.update(connection, "INSERT INTO TABLETEST1 VALUES (?)", "CCC");
    connection.commit();

    List<String> values = queryRunner.query(connection, "SELECT * FROM TABLETEST1 ORDER BY ACOLUMN ASC",
            new ColumnListHandler<String>());

    connection.commit();

    connection.close();

    assertEquals("AAA", values.get(0));
    assertEquals("BBB", values.get(1));
    assertEquals("CCC", values.get(2));

    Statistics statistics = dsp.getStatistics();
    assertTrue(statistics.getCacheHits() > 0);
    assertTrue(statistics.getCacheMiss() > 0);
    assertEquals(1, statistics.getConnectionsRequested());
    assertEquals(4, statistics.getStatementsPrepared());

    dsp.close();
}

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

/**
 * Recupera la suma total de todos los conceptos de todas las facturas del tipo que se envie por parametro
 * @param billType tipo de factura//from w w  w.j  av  a  2s  .co m
 */
public static double getTotalFacturasOriginal(String billType) throws Exception {

    Connection con = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    LineNumberReader file = null;
    double result = -1;

    try {
        log.info("RECOVERING TOTAL 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= ?";

        pstmt = con.prepareStatement(sql);
        pstmt.setString(1, billType);

        rs = pstmt.executeQuery();

        while (rs.next()) {
            result = rs.getDouble(1);
            log.info("\t" + result);
        }

        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;
}