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.homeless.TestUtils.java

public static void executeSql(Connection connection, String sqlStatements, String schema) {
    try {//  ww  w  . j a  v  a2 s . c o m
        String str = sqlStatements.replaceAll("<SCHEMA>", schema);
        str = str.replaceAll("<DIR>", SpliceUnitTest.getResourceDirectory());
        for (String s : str.split(";")) {
            String trimmed = s.trim();
            if (!trimmed.equals("")) {
                Statement stmt = connection.createStatement();
                stmt.execute(s);
                connection.commit();
            }
        }
    } catch (Exception e) {
        throw new RuntimeException("Error running SQL statements: " + sqlStatements, e);
    }
}

From source file:com.mirth.connect.server.util.DatabaseUtil.java

public static void executeScript(List<String> script, boolean ignoreErrors) throws Exception {
    SqlSessionManager sqlSessionManger = SqlConfig.getSqlSessionManager();

    Connection conn = null;
    ResultSet resultSet = null;//from w ww  . j a  v  a2  s . c om
    Statement statement = null;

    try {
        sqlSessionManger.startManagedSession();
        conn = sqlSessionManger.getConnection();
        /*
         * Set auto commit to false or an exception will be thrown when trying to rollback
         */
        conn.setAutoCommit(false);
        statement = conn.createStatement();

        for (String statementString : script) {
            statementString = statementString.trim();
            if (statementString.length() > 0) {
                try {
                    statement.execute(statementString);
                    conn.commit();
                } catch (SQLException se) {
                    if (!ignoreErrors) {
                        throw se;
                    } else {
                        logger.error("Error was encountered and ignored while executing statement: "
                                + statementString, se);
                        conn.rollback();
                    }
                }
            }
        }

    } catch (Exception e) {
        throw new Exception(e);
    } finally {
        DbUtils.closeQuietly(statement);
        DbUtils.closeQuietly(resultSet);
        DbUtils.closeQuietly(conn);
        sqlSessionManger.close();
    }
}

From source file:gridool.util.jdbc.JDBCUtils.java

public static int[] batch(Connection conn, String... sqls) throws SQLException {
    final boolean autoCommit = conn.getAutoCommit();
    if (autoCommit) {
        conn.setAutoCommit(false);//from  ww w.  ja  v a 2s  .c  o m
    }
    Statement stmt = null;
    int[] rows = null;
    try {
        stmt = conn.createStatement();
        for (int i = 0; i < sqls.length; i++) {
            verboseQuery(sqls[i], (Object[]) null);
            stmt.addBatch(sqls[i]);
        }
        rows = stmt.executeBatch();
        conn.commit();
    } catch (SQLException e) {
        conn.rollback();
        rethrow(e, sqls);
    } finally {
        close(stmt);
    }
    // change back commit mode.
    if (autoCommit) {
        conn.setAutoCommit(true);
    }
    return rows;
}

From source file:com.stratelia.webactiv.util.DBUtil.java

protected static int getMaxId(Connection privateConnection, String tableName, String idName)
        throws SQLException {
    // tentative d'update
    SilverTrace.debug("util", "DBUtil.getNextId", "dBName = " + tableName);
    try {//from  ww  w . java 2s. c om
        int max = updateMaxFromTable(privateConnection, tableName);
        privateConnection.commit();
        return max;
    } catch (Exception e) {
        // l'update n'a rien fait, il faut recuperer une valeur par defaut.
        // on recupere le max (depuis la table existante du composant)
        SilverTrace.debug("util", "DBUtil.getNextId",
                "impossible d'updater, if faut recuperer la valeur initiale", e);
    }
    int max = getMaxFromTable(privateConnection, tableName, idName);
    PreparedStatement createStmt = null;
    try {
        // on enregistre le max
        String createStatement = "INSERT INTO UniqueId (maxId, tableName) VALUES (?, ?)";
        createStmt = privateConnection.prepareStatement(createStatement);
        createStmt.setInt(1, max);
        createStmt.setString(2, tableName.toLowerCase());
        createStmt.executeUpdate();
        privateConnection.commit();
        return max;
    } catch (Exception e) {
        // impossible de creer, on est en concurence, on reessaye l'update.
        SilverTrace.debug("util", "DBUtil.getNextId", "impossible de creer, if faut reessayer l'update", e);
        rollback(privateConnection);
    } finally {
        close(createStmt);
    }
    max = updateMaxFromTable(privateConnection, tableName);
    privateConnection.commit();
    return max;
}

From source file:com.hangum.tadpole.rdb.core.util.bander.cubrid.CubridExecutePlanUtils.java

/**
 * cubrid execute plan/*from  w  ww  .  j a v a2s .c  o m*/
 * 
 * @param userDB
 * @param sql
 * @return
 * @throws Exception
 */
public static String plan(UserDBDAO userDB, String sql) throws Exception {
    if (!sql.toLowerCase().startsWith("select")) {
        logger.error("[cubrid execute plan ]" + sql);
        throw new Exception("This statment not select. please check.");
    }
    Connection conn = null;
    ResultSet rs = null;
    PreparedStatement pstmt = null;

    try {
        Class.forName("cubrid.jdbc.driver.CUBRIDDriver");
        conn = DriverManager.getConnection(userDB.getUrl(), userDB.getUsers(), userDB.getPasswd());
        conn.setAutoCommit(false); //     auto commit? false  .      

        sql = StringUtils.trim(sql).substring(6);
        if (logger.isDebugEnabled())
            logger.debug("[qubrid modifying query]" + sql);
        sql = "select " + RECOMPILE + sql;

        pstmt = conn.prepareStatement(sql);
        ((CUBRIDStatement) pstmt).setQueryInfo(true);
        rs = pstmt.executeQuery();

        String plan = ((CUBRIDStatement) pstmt).getQueryplan(); //  ?    .
        conn.commit();

        if (logger.isDebugEnabled())
            logger.debug("cubrid plan text : " + plan);

        return plan;

    } finally {
        if (rs != null)
            rs.close();
        if (pstmt != null)
            pstmt.close();
        if (conn != null)
            conn.close();
    }
}

From source file:com.redhat.rhn.common.db.datasource.test.AdvDataSourceTest.java

protected static void oneTimeSetup() throws Exception {
    Session session = null;//  w  w w.ja  va 2  s  .co  m
    Connection c = null;
    Statement stmt = null;
    try {
        session = HibernateFactory.getSession();
        c = session.connection();
        stmt = c.createStatement();
        stmt.executeQuery("select 1 from adv_datasource");
    } catch (SQLException e) {
        // Couldn't select 1, so the table didn't exist, create it
        stmt.execute("create table adv_datasource " + "( " + "  foobar VarChar2(32),"
                + "  test_column VarChar2(25)," + "  pin    number, " + "  id     number"
                + "         constraint adv_datasource_pk primary key" + ")");
        stmt.execute("insert into adv_datasource(foobar, id) " + "values ('Blarg', 1)");
        c.commit();
    } finally {
        HibernateHelper.cleanupDB(stmt);
    }
}

From source file:ccc.cli.StringToDecConverter.java

private void commit(final Connection con) {
    try {// w  ww .j av a2  s. co  m
        con.commit();
    } catch (final SQLException e) {
        LOG.fatal("Error committing changes", e);
        try {
            LOG.error("Rolling back connection");
            con.rollback();
            LOG.info("Rolled back connection successfully");
        } catch (final SQLException e1) {
            LOG.error("Failed to rollback connection");
        }
    }
}

From source file:com.stratelia.webactiv.util.DBUtil.java

private static int updateMaxFromTable(Connection connection, String tableName) throws SQLException {
    String table = tableName.toLowerCase(Locale.ROOT);
    int max = 0;/*from  w w w.  j a  v a2s.co  m*/
    PreparedStatement prepStmt = null;
    int count = 0;
    try {
        prepStmt = connection.prepareStatement("UPDATE UniqueId SET maxId = maxId + 1 WHERE tableName = ?");
        prepStmt.setString(1, table);
        count = prepStmt.executeUpdate();
        connection.commit();
    } catch (SQLException sqlex) {
        rollback(connection);
        throw sqlex;
    } finally {
        close(prepStmt);
    }

    if (count == 1) {
        PreparedStatement selectStmt = null;
        ResultSet rs = null;
        try {
            // l'update c'est bien passe, on recupere la valeur
            selectStmt = connection.prepareStatement("SELECT maxId FROM UniqueId WHERE tableName = ?");
            selectStmt.setString(1, table);
            rs = selectStmt.executeQuery();
            if (!rs.next()) {
                SilverTrace.error("util", "DBUtil.getNextId", "util.MSG_NO_RECORD_FOUND");
                throw new RuntimeException("Erreur Interne DBUtil.getNextId()");
            }
            max = rs.getInt(1);
        } finally {
            close(rs, selectStmt);
        }
        return max;
    }
    throw new SQLException("Update impossible : Ligne non existante");
}

From source file:gridool.db.catalog.DistributionCatalog.java

private static boolean prepareTables(@Nonnull final Connection conn, final String distributionTableName,
        final boolean autoCommit) {
    final String ddl = "CREATE TABLE \"" + distributionTableName
            + "\"(distkey varchar(50) NOT NULL, node varchar(50) NOT NULL, masternode varchar(50), state SMALLINT NOT NULL);\n"
            + "CREATE TABLE \"" + partitionkeyTableName
            + "\"(tablename varchar(30) PRIMARY KEY, tplprefix varchar(20) NOT NULL, id " + tableIdSQLDataType
            + " auto_increment);";
    try {/*  w w  w .  j  a v  a2  s.c  om*/
        JDBCUtils.update(conn, ddl);
        if (!autoCommit) {
            conn.commit();
        }
    } catch (SQLException e) {
        // avoid table already exists error
        if (!autoCommit) {
            try {
                conn.rollback();
            } catch (SQLException sqle) {
                LOG.warn("failed to rollback", sqle);
            }
        }
        return false;
    }
    return true;
}

From source file:com.aurel.track.admin.customize.category.filter.PredefinedQueryBL.java

/**
 * We forgot to add also the watcher at Migrate400To410.
 * This will be added at Migrate410To412
 * Although it will not appear implicitly in the menu items for users we should define it
 * because otherwise the watcher part of MyItems dashboard does not work
 *///w  w  w . j a  v  a  2  s.c  om
public static void addWatcherFilter() {
    LOGGER.info("Add watcher filters");
    FilterFacade filterFacade = FilterFacadeFactory.getInstance()
            .getFilterFacade(TQueryRepositoryBean.QUERY_PURPOSE.TREE_FILTER, true);
    // Get not closed stateIDs
    List<TStateBean> notClosedStateBeans = StatusBL.loadNotClosedStates();
    List<Integer> notClosedStateIDs = GeneralUtils.createIntegerListFromBeanList(notClosedStateBeans);
    Integer[] notClosedStatesArr = GeneralUtils.createIntegerArrFromCollection(notClosedStateIDs);
    ILabelBean watcherBean = filterFacade.getByKey(PREDEFINED_QUERY.WATCHER_ITEMS);
    if (watcherBean == null) {
        Connection cono = null;
        try {
            cono = InitDatabase.getConnection();
            Statement ostmt = cono.createStatement();
            cono.setAutoCommit(false);
            ostmt.executeUpdate(addPredefinedQueryClob(PREDEFINED_QUERY.WATCHER_ITEMS,
                    PredefinedQueryBL.getWatcherItemsExpression(notClosedStatesArr)));
            ostmt.executeUpdate(addPredefinedQuery(PREDEFINED_QUERY.WATCHER_ITEMS, "I''m watcher"));
            cono.commit();
            cono.setAutoCommit(true);
        } catch (Exception e) {
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        } finally {
            try {
                if (cono != null) {
                    cono.close();
                }
            } catch (Exception e) {
                LOGGER.info("Closing the connection failed with " + e.getMessage());
                LOGGER.debug(ExceptionUtils.getStackTrace(e));
            }
        }
    }
}