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:desktop.olayinka.file.transfer.model.DerbyJDBCHelper.java

private DerbyJDBCHelper() {
    try {// w  ww .  j  av a  2  s  .  com
        System.out.println(DB_URL);

        //ensure database is created
        String dbUrl = "jdbc:derby:" + DB_FILE.getAbsolutePath() + ";create=true;user=" + DB_USER + ";password="
                + DB_PWD;
        System.out.println(dbUrl);
        Connection mConnection;
        try {
            Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
            mConnection = DriverManager.getConnection(dbUrl);
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
            return;
        }
        onStart(mConnection);
        onUpgrade(mConnection);
        mConnection.commit();
        mConnection.close();

        //instantiate persistence unit
        EntityManagerFactory managerFactory = null;
        Map<String, String> persistenceMap = new HashMap<String, String>();

        persistenceMap.put("javax.persistence.jdbc.url", DB_URL);
        persistenceMap.put("javax.persistence.jdbc.user", DB_USER);
        persistenceMap.put("javax.persistence.jdbc.password", DB_PWD);

        URL resource = ClassLoader.getSystemResource("");
        File file = new File(String.valueOf(resource));

        managerFactory = Persistence.createEntityManagerFactory("A2PPU", persistenceMap);
        mManager = managerFactory.createEntityManager();

        deviceProvider = new JDBCDeviceProvider(mManager);

    } catch (Exception except) {
        except.printStackTrace();
        System.exit(1);
    }
}

From source file:com.agiletec.plugins.jpcontentfeedback.aps.system.services.contentfeedback.comment.CommentDAO.java

@Override
public void updateStatus(int id, int status) {
    Connection conn = null;
    PreparedStatement stat = null;
    try {/* w  ww .ja  v  a2 s. c o  m*/
        conn = this.getConnection();
        conn.setAutoCommit(false);
        stat = conn.prepareStatement(UPDATE_STATUS_COMMENT);
        stat.setInt(1, status);
        stat.setInt(2, id);
        stat.executeUpdate();
        conn.commit();
    } catch (Throwable t) {
        this.executeRollback(conn);
        _logger.error("Error updating comment status to {} for comment {} ", status, id, t);
        throw new RuntimeException("Error updating comment status", t);
    } finally {
        closeDaoResources(null, stat, conn);
    }

}

From source file:de.codecentric.multitool.db.DBUnitLibrary.java

/**
 * Liest einen Einzelwert aus einer Tabellenabfrage
 * //from w  ww  .  j ava 2s  .  c o  m
 * Beispiel: | Execute SQL | ACSD_FULL | DELETE FROM table |
 */
public void executeSQL(String dsName, String sql) throws IllegalArgumentException, SQLException {
    Statement statement = null;
    try {
        Connection con = getConnection(dsName);
        statement = con.createStatement();
        statement.execute(sql);
        con.commit();

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

From source file:de.walware.statet.r.internal.core.pkgmanager.DB.java

private void clean(final List<String> removeLibPath) throws SQLException {
    final Connection connection = getConnection();
    try (final PreparedStatement statement = connection.prepareStatement(REnv.LibPaths.OP_delete_byPath)) {
        for (final String libPath : removeLibPath) {
            statement.setString(1, libPath);
            statement.execute();/*from  www . j  a  v  a 2s .c o m*/
        }

        connection.commit();
    } catch (final SQLException e) {
        closeOnError();
        throw e;
    }
}

From source file:com.stratio.ingestion.sink.jdbc.JDBCSinkTest.java

@Test
public void mappedWithDerby() throws Exception {
    FileUtils.deleteDirectory(new File("test_derby_db"));
    Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
    Connection conn = DriverManager.getConnection("jdbc:derby:test_derby_db;create=true");
    conn.prepareStatement(//from www.j  a  va2  s.c  o  m
            "CREATE TABLE TEST (myInteger INT, myString VARCHAR(255), myId INT NOT NULL GENERATED ALWAYS AS IDENTITY \n"
                    + "\t(START WITH 1, INCREMENT BY 1), PRIMARY KEY(myId))")
            .execute();
    conn.commit();
    conn.close();

    Context ctx = new Context();
    ctx.put("driver", "org.apache.derby.jdbc.EmbeddedDriver");
    ctx.put("connectionString", "jdbc:derby:test_derby_db");
    ctx.put("table", "test");
    ctx.put("sqlDialect", "DERBY");
    ctx.put("batchSize", "1");

    JDBCSink jdbcSink = new JDBCSink();

    Configurables.configure(jdbcSink, ctx);

    Context channelContext = new Context();
    channelContext.put("capacity", "10000");
    channelContext.put("transactionCapacity", "200");

    Channel channel = new MemoryChannel();
    channel.setName("junitChannel");
    Configurables.configure(channel, channelContext);

    jdbcSink.setChannel(channel);

    channel.start();
    jdbcSink.start();

    Transaction tx = channel.getTransaction();
    tx.begin();

    Map<String, String> headers = new HashMap<String, String>();
    headers.put("myString", "bar"); // Overwrites the value defined in JSON body
    headers.put("myInteger", "64");
    headers.put("myBoolean", "true");
    headers.put("myDouble", "1.0");
    headers.put("myNull", "foobar");

    Date myDate = new Date();
    headers.put("myDate", Long.toString(myDate.getTime()));

    headers.put("myString2", "baz");

    Event event = EventBuilder.withBody(new byte[0], headers);
    channel.put(event);

    tx.commit();
    tx.close();

    jdbcSink.process();

    jdbcSink.stop();
    channel.stop();

    conn = DriverManager.getConnection("jdbc:derby:test_derby_db");
    ResultSet resultSet = conn.prepareStatement("SELECT * FROM TEST").executeQuery();
    resultSet.next();
    assertThat(resultSet.getInt("myInteger")).isEqualTo(64);
    assertThat(resultSet.getString("myString")).isEqualTo("bar");
    conn.close();

    try {
        DriverManager.getConnection("jdbc:derby:;shutdown=true");
    } catch (SQLException ex) {

    }
}

From source file:com.trackplus.ddl.DataWriter.java

private static int executeScript(String fileName, Connection con, String endOfStatement) throws DDLException {
    BufferedReader bufferedReader = createBufferedReader(fileName);

    String line;/* w w w . ja v  a  2  s  .com*/
    StringBuilder sql = new StringBuilder();

    Statement stmt = MetaDataBL.createStatement(con);

    int idx = 0;
    try {
        while ((line = bufferedReader.readLine()) != null) {
            sql.append(line);
            if (line.endsWith(endOfStatement)) {
                String s = sql.substring(0, sql.length() - endOfStatement.length());
                idx++;
                if (idx % 5000 == 0) {
                    LOGGER.info(idx + " inserts executed...");
                }
                executeUpdate(con, stmt, s);
                sql.setLength(0);
            } else {
                sql.append("\n");
            }
        }
    } catch (IOException e) {
        throw new DDLException(e.getMessage(), e);
    }

    //close file
    try {
        bufferedReader.close();
    } catch (IOException e) {
        throw new DDLException(e.getMessage(), e);
    }

    //close connection
    try {
        stmt.close();
        con.commit();
        con.setAutoCommit(true);
    } catch (SQLException e) {
        throw new DDLException(e.getMessage(), e);
    }

    return idx;
}

From source file:eu.europa.esig.dss.client.crl.JdbcCacheCRLSource.java

/**
 * Create the cache crl table if it does not exist
 *
 * @throws java.sql.SQLException//  w ww.  j a v  a 2s  .  c  o m
 */
private void createTable() throws SQLException {

    Connection c = null;
    Statement s = null;
    try {
        c = getDataSource().getConnection();
        s = c.createStatement();
        s.executeQuery(sqlInitCreateTable);
        c.commit();
    } finally {
        closeQuietly(c, s, null);
    }

}

From source file:org.web4thejob.module.JobletInstallerImpl.java

@Override
@SuppressWarnings("unchecked")
public <E extends Exception> List<E> install(List<Joblet> joblets) {
    List<E> exceptions = new ArrayList<E>();

    try {/*from  ww w.j a  v  a2  s  . c o  m*/

        final Configuration configuration = new Configuration();
        configuration.setProperty(AvailableSettings.DIALECT,
                connInfo.getProperty(DatasourceProperties.DIALECT));
        configuration.setProperty(AvailableSettings.DRIVER, connInfo.getProperty(DatasourceProperties.DRIVER));
        configuration.setProperty(AvailableSettings.URL, connInfo.getProperty(DatasourceProperties.URL));
        configuration.setProperty(AvailableSettings.USER, connInfo.getProperty(DatasourceProperties.USER));
        configuration.setProperty(AvailableSettings.PASS, connInfo.getProperty(DatasourceProperties.PASSWORD));

        final ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties()).build();

        if (StringUtils.hasText(connInfo.getProperty(DatasourceProperties.SCHEMA_SYNTAX))) {
            String schemaSyntax = connInfo.getProperty(DatasourceProperties.SCHEMA_SYNTAX);
            Connection connection = serviceRegistry.getService(ConnectionProvider.class).getConnection();

            for (Joblet joblet : joblets) {
                for (String schema : joblet.getSchemas()) {
                    Statement statement = connection.createStatement();
                    statement.executeUpdate(schemaSyntax.replace("%s", schema));
                    statement.close();
                }
            }

            if (!connection.getAutoCommit()) {
                connection.commit();
            }
        }

        for (Joblet joblet : joblets) {
            for (Resource resource : joblet.getResources()) {
                configuration.addInputStream(resource.getInputStream());
            }
        }

        SchemaExport schemaExport = new SchemaExport(serviceRegistry, configuration);
        schemaExport.execute(Target.EXPORT, SchemaExport.Type.CREATE);
        exceptions.addAll(schemaExport.getExceptions());

    } catch (Exception e) {
        exceptions.add((E) e);
    }

    return exceptions;

}

From source file:com.wso2telco.core.dbutils.DbUtils.java

/**
 * Disconnect./*from  w  w w  . java2 s  . c o m*/
 *
 * @param con
 *            the con
 * @throws Exception
 *             the exception
 */
public void disconnect(Connection con) throws Exception {
    System.out.println();

    // makes all changes made since the previous commit/rollback permanent
    // and releases any database locks currrently held by the Connection.
    con.commit();

    // immediately disconnects from database and releases JDBC resources
    con.close();
}

From source file:com.flexive.core.storage.GenericDBStorage.java

/**
 * {@inheritDoc}//from www . j  ava  2  s .c om
 */
@Override
public void importDivision(Connection _con, ZipFile zip) throws Exception {
    long startTime = System.currentTimeMillis();
    GenericDivisionImporter importer = getDivisionImporter();
    FxDivisionExportInfo exportInfo = importer.getDivisionExportInfo(zip);
    if (FxSharedUtils.getDBVersion() != exportInfo.getSchemaVersion()) {
        LOG.warn("DB Version mismatch! Current:" + FxSharedUtils.getDBVersion() + ", exported schema:"
                + exportInfo.getSchemaVersion());
    }
    boolean isNonTX = importer.importRequiresNonTXConnection();
    Connection con = isNonTX ? Database.getNonTXDataSource().getConnection() : _con;

    boolean autoCommit = false;
    if (isNonTX) {
        autoCommit = con.getAutoCommit();
        con.setAutoCommit(false);
        con.commit(); //ensure a "clean" connection
    }
    Exception inner = null;
    try {
        importer.wipeDivisionData(con);
        if (isNonTX)
            con.commit();
        Statement stmt = con.createStatement();
        if (isNonTX)
            con.commit();
        try {
            importer.importLanguages(con, zip);
            if (isNonTX)
                con.commit();
            importer.importMandators(con, zip);
            if (isNonTX)
                con.commit();
            importer.importSecurity(con, zip);
            if (isNonTX)
                con.commit();
            importer.importWorkflows(con, zip);
            if (isNonTX)
                con.commit();
            importer.importConfigurations(con, zip);
            if (isNonTX)
                con.commit();
            importer.importBinaries(con, zip);
            if (isNonTX)
                con.commit();
            stmt.execute(getReferentialIntegrityChecksStatement(false));
            importer.importStructures(con, zip);
            if (isNonTX)
                con.commit();
            importer.importHierarchicalContents(con, zip);
            if (isNonTX)
                con.commit();
            importer.importScripts(con, zip);
            if (isNonTX)
                con.commit();
            importer.importTree(con, zip);
            if (isNonTX)
                con.commit();
            importer.importHistory(con, zip);
            if (isNonTX)
                con.commit();
            importer.importResources(con, zip);
            if (isNonTX)
                con.commit();
            importer.importBriefcases(con, zip);
            if (isNonTX)
                con.commit();
            importer.importFlatStorages(con, zip, exportInfo);
            if (isNonTX)
                con.commit();
            importer.importSequencers(con, zip);
            if (isNonTX)
                con.commit();
        } catch (Exception e) {
            if (isNonTX)
                con.rollback();
            inner = e;
            throw e;
        } finally {
            if (isNonTX)
                con.commit();
            stmt.execute(getReferentialIntegrityChecksStatement(true));
        }
        if (isNonTX)
            con.commit();
        //rebuild fulltext index
        FulltextIndexer ft = StorageManager.getStorageImpl().getContentStorage(TypeStorageMode.Hierarchical)
                .getFulltextIndexer(null, con);
        ft.rebuildIndex();
        if (isNonTX)
            con.commit();
    } catch (Exception e) {
        if (isNonTX)
            con.rollback();
        if (inner != null) {
            LOG.error(e);
            throw inner;
        }
        throw e;
    } finally {
        if (isNonTX) {
            con.commit();
            con.setAutoCommit(autoCommit);
            Database.closeObjects(GenericDBStorage.class, con, null);
        }
        LOG.info(" Importing took " + FxFormatUtils.formatTimeSpan((System.currentTimeMillis() - startTime)));
    }
}