Example usage for java.sql Connection setAutoCommit

List of usage examples for java.sql Connection setAutoCommit

Introduction

In this page you can find the example usage for java.sql Connection setAutoCommit.

Prototype

void setAutoCommit(boolean autoCommit) throws SQLException;

Source Link

Document

Sets this connection's auto-commit mode to the given state.

Usage

From source file:localdomain.localhost.CasInitializer.java

@ManagedOperation
public void deleteUser(@NotNull String username) {
    Connection cnn = null;
    PreparedStatement stmt = null;
    try {/*from  w  ww.  j a va  2s.c  o  m*/
        cnn = dataSource.getConnection();
        cnn.setAutoCommit(false);
        stmt = cnn.prepareStatement("delete from `" + tableUsers + "` where `" + fieldUser + "` like ?");
        stmt.setString(1, username);
        int rowCount = stmt.executeUpdate();
        if (rowCount == 0) {
            throw new NoSuchElementException("No user '" + username + "' found");
        } else if (rowCount == 1) {
            logger.info("User '" + username + "' was deleted");
        } else {
            new IllegalArgumentException(
                    "More (" + rowCount + ") than 1 row deleted for username '" + username + "', rollback");
        }
        logger.info("User '" + username + "' deleted");
        cnn.commit();
    } catch (RuntimeException e) {
        rollbackQuietly(cnn);
        String msg = "Exception deleting user '" + username + "': " + e;
        logger.warn(msg, e);
        throw new RuntimeException(msg);
    } catch (SQLException e) {
        rollbackQuietly(cnn);

        String msg = "Exception deleting user '" + username + "': " + e;
        logger.warn(msg, e);
        throw new RuntimeException(msg);
    } finally {
        closeQuietly(cnn, stmt);
    }
}

From source file:localdomain.localhost.CasInitializer.java

@ManagedOperation
public void changeUserPassword(@NotNull String username, @NotNull String clearTextPassword) {
    Connection cnn = null;
    PreparedStatement stmt = null;
    try {/*www.j  a v a 2s .c  om*/
        cnn = dataSource.getConnection();
        cnn.setAutoCommit(false);
        stmt = cnn.prepareStatement(
                "update `" + tableUsers + "` set `" + fieldPassword + "` = ? where `" + fieldUser + "` like ?");
        stmt.setString(1, passwordEncoder.encode(clearTextPassword));
        stmt.setString(2, username);
        int rowCount = stmt.executeUpdate();
        if (rowCount == 0) {
            throw new NoSuchElementException("No user '" + username + "' found");
        } else if (rowCount == 1) {
            logger.info("Password of user '" + username + "' was updated");
        } else {
            new IllegalArgumentException(
                    "More (" + rowCount + ") than 1 row deleted for username '" + username + "', rollback");
        }
        logger.info("User '" + username + "' deleted");
        cnn.commit();
    } catch (RuntimeException e) {
        rollbackQuietly(cnn);
        String msg = "Exception changing password for user '" + username + "': " + e;
        logger.warn(msg, e);
        throw new RuntimeException(msg);
    } catch (SQLException e) {
        rollbackQuietly(cnn);
        String msg = "Exception changing password for user '" + username + "': " + e;
        logger.warn(msg, e);
        throw new RuntimeException(msg);
    } finally {
        closeQuietly(cnn, stmt);
    }
}

From source file:com.fileanalyzer.dao.impl.FilesDAOImpl.java

@Override
public void doFinal(final Connection con, final PreparedStatement preparedStatement) {
    if (preparedStatement != null) {
        try {//ww  w .ja  v a2s .c  om
            preparedStatement.close();
        } catch (SQLException ex) {
            log.error(ex);
        }
    }
    try {
        con.setAutoCommit(true);
    } catch (SQLException ex) {
        log.error("setAutoCommit(true)", ex);
    }
    if (con != null) {
        try {
            con.close();
        } catch (SQLException ex) {
            log.error(ex);
        }
    }
}

From source file:com.google.enterprise.connector.salesforce.storetype.DBStore.java

public DocListEntry getDocsImmediatelyAfter(String checkpoint) {
    DatabaseMetaData dbm = null;//ww  w. ja v  a 2  s .c  o  m
    Connection connection = null;

    try {

        connection = ds.getConnection();
        connection.setAutoCommit(true);

        dbm = connection.getMetaData();
        //get the most recent database row after 'checkpoint'
        if (dbm.getDatabaseProductName().equals("MySQL")) {
            Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);
            String update_stmt = "select crawl_set,insert_timestamp,UNCOMPRESS(crawl_data) as cdata from "
                    + this.instance_table + " where crawl_set>" + checkpoint + "  LIMIT 1";
            logger.log(Level.FINER, update_stmt);
            ResultSet rs = statement.executeQuery(update_stmt);

            boolean ret_rows = rs.first();

            if (!ret_rows) {
                logger.log(Level.FINER, "No Rows Returned.");
                connection.close();
                return null;
            }
            BigDecimal crawl_set = null;
            String crawl_data = null;
            while (ret_rows) {
                crawl_set = rs.getBigDecimal("crawl_set");
                //crawl_data = rs.getString("crawl_data");
                crawl_data = rs.getString("cdata");
                ret_rows = rs.next();
            }

            rs.close();
            statement.close();
            connection.close();

            //BASE64 DECODE 
            byte[] byte_decoded_entry = org.apache.commons.codec.binary.Base64
                    .decodeBase64(crawl_data.getBytes());
            crawl_data = new String(byte_decoded_entry);

            logger.log(Level.INFO, "Returning from DBStore. Index Value: " + crawl_set.toPlainString());
            logger.log(Level.FINEST, "Returning from DBStore. " + crawl_data);
            DocListEntry dret = new DocListEntry(crawl_set.toPlainString(), crawl_data);
            return dret;
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Unable to retrieve docListEntry " + ex);
    }
    return new DocListEntry(checkpoint, null);
}

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

@Test
public void testJdbcEscapedTableName() throws Exception {
    // Test a JDBC-based import of a table whose name is
    // a reserved sql keyword (and is thus `quoted`)
    final String RESERVED_TABLE_NAME = "TABLE";
    SqoopOptions options = new SqoopOptions(MySQLTestUtils.CONNECT_STRING, RESERVED_TABLE_NAME);
    options.setUsername(MySQLTestUtils.getCurrentUser());
    ConnManager mgr = new MySQLManager(options);

    Connection connection = null;
    Statement st = null;/*from  ww w .j av a 2 s  .c  o  m*/

    try {
        connection = mgr.getConnection();
        connection.setAutoCommit(false);
        st = connection.createStatement();

        // create the database table and populate it with data.
        st.executeUpdate("DROP TABLE IF EXISTS `" + RESERVED_TABLE_NAME + "`");
        st.executeUpdate("CREATE TABLE `" + RESERVED_TABLE_NAME + "` ("
                + "id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, " + "name VARCHAR(24) NOT NULL, "
                + "start_date DATE, " + "salary FLOAT, " + "dept VARCHAR(32))");

        st.executeUpdate("INSERT INTO `" + RESERVED_TABLE_NAME + "` VALUES("
                + "2,'Aaron','2009-05-14',1000000.00,'engineering')");
        connection.commit();
    } finally {
        if (null != st) {
            st.close();
        }

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

    String[] expectedResults = { "2,Aaron,2009-05-14,1000000.0,engineering", };

    doImport(false, false, RESERVED_TABLE_NAME, expectedResults, null);
}

From source file:kenh.xscript.database.elements.Execute.java

@Processing
public int process_Source_Var_SqlBean(@Attribute(ATTRIBUTE_SQL) SQLBean sqlBean,
        @Attribute(ATTRIBUTE_VARIABLE) String var, @Attribute(ATTRIBUTE_REF) DataSource source)
        throws UnsupportedScriptException {
    java.sql.Connection conn = null;
    try {/*from  w w w  .  j  a  va  2  s  .co m*/
        conn = source.getConnection();
        conn.setAutoCommit(true);
        return executeSQL(sqlBean, var, conn);
    } catch (java.sql.SQLException sqle) {
        throw new UnsupportedScriptException(this, sqle);
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (Exception e_) {
            }
            conn = null;
        }
    }
}

From source file:net.gcolin.simplerepo.search.SearchController.java

public void add(final Repository repository, File pomFile, Model model) throws IOException {
    SearchResult result = buildResult(repository.getName(), pomFile, model);
    try {/* www.j  a  v a2  s.  c om*/
        Connection connection = null;
        try {
            connection = datasource.getConnection();
            connection.setAutoCommit(false);
            QueryRunner run = new QueryRunner();
            Long artifactIdx = run.query(connection, "select id from artifact where groupId=? and artifactId=?",
                    getLong, result.getGroupId(), result.getArtifactId());
            if (artifactIdx == null) {
                artifactIdx = run.query(connection, "select artifact from artifactindex", getLong);
                run.update(connection, "update artifactindex set artifact=?", artifactIdx + 1);
                run.update(connection, "insert into artifact (id,groupId,artifactId) VALUES (?,?,?)",
                        artifactIdx, result.getGroupId(), result.getArtifactId());
            }
            Long versionId = run.query(connection, "select version from artifactindex", getLong);
            run.update(connection, "update artifactindex set version=?", versionId + 1);
            run.update(connection,
                    "insert into artifactversion(artifact_id,id,version,reponame) VALUES (?,?,?,?)",
                    artifactIdx, versionId, result.getVersion(), result.getRepoName());
            for (ResultType res : result.getTypes()) {
                run.update(connection,
                        "insert into artifacttype(version_id,packaging,classifier) VALUES (?,?,?)", versionId,
                        res.getName(), res.getClassifier());
            }
            connection.commit();
        } catch (SQLException ex) {
            connection.rollback();
            throw ex;
        } finally {
            DbUtils.close(connection);
        }
    } catch (SQLException ex) {
        logger.log(Level.SEVERE, null, ex);
        throw new IOException(ex);
    }
}

From source file:com.agiletec.plugins.jpcrowdsourcing.aps.system.services.ideainstance.IdeaInstanceDAO.java

@Override
public void insertIdeaInstance(IdeaInstance ideainstance) {
    PreparedStatement stat = null;
    Connection conn = null;
    try {/*from ww  w.j a  v a2 s .  co  m*/
        conn = this.getConnection();
        conn.setAutoCommit(false);
        this.insertIdeaInstance(ideainstance, conn);
        this.insertIdeaInstanceGroups(ideainstance.getCode(), ideainstance.getGroups(), conn);
        conn.commit();
    } catch (Throwable t) {
        this.executeRollback(conn);
        _logger.error("Error creating ideainstance", t);
        throw new RuntimeException("Error creating ideainstance", t);
    } finally {
        this.closeDaoResources(null, stat, conn);
    }
}

From source file:com.agiletec.plugins.jpcrowdsourcing.aps.system.services.ideainstance.IdeaInstanceDAO.java

@Override
public void updateIdeaInstance(IdeaInstance ideainstance) {
    PreparedStatement stat = null;
    Connection conn = null;
    try {//from  w w w  . ja  v a2 s. com
        conn = this.getConnection();
        conn.setAutoCommit(false);
        this.updateIdeaInstance(ideainstance, conn);
        this.insertIdeaInstanceGroups(ideainstance.getCode(), ideainstance.getGroups(), conn);
        conn.commit();
    } catch (Throwable t) {
        this.executeRollback(conn);
        _logger.error("Error updating ideainstance", t);
        throw new RuntimeException("Error updating ideainstance", t);
    } finally {
        this.closeDaoResources(null, stat, conn);
    }
}

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

@Test
public void testJdbcEscapedColumnName() throws Exception {
    // Test a JDBC-based import of a table with a column whose name is
    // a reserved sql keyword (and is thus `quoted`).
    final String TABLE_NAME = "mysql_escaped_col_table";
    setCurTableName(TABLE_NAME);/*  w  w w .jav  a  2  s  . c  om*/
    SqoopOptions options = new SqoopOptions(MySQLTestUtils.CONNECT_STRING, TABLE_NAME);
    options.setUsername(MySQLTestUtils.getCurrentUser());
    ConnManager mgr = new MySQLManager(options);

    Connection connection = null;
    Statement st = null;

    try {
        connection = mgr.getConnection();
        connection.setAutoCommit(false);
        st = connection.createStatement();

        // create the database table and populate it with data.
        st.executeUpdate("DROP TABLE IF EXISTS " + TABLE_NAME);
        st.executeUpdate("CREATE TABLE " + TABLE_NAME + " (" + "id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, "
                + "`table` VARCHAR(24) NOT NULL, " + "`CREATE` DATE, " + "salary FLOAT, "
                + "dept VARCHAR(32))");

        st.executeUpdate(
                "INSERT INTO " + TABLE_NAME + " VALUES(" + "2,'Aaron','2009-05-14',1000000.00,'engineering')");
        connection.commit();
    } finally {
        if (null != st) {
            st.close();
        }

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

    String[] expectedResults = { "2,Aaron,2009-05-14,1000000.0,engineering", };

    doImport(false, false, TABLE_NAME, expectedResults, null);
}