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:com.cloudera.sqoop.manager.MySQLAuthTest.java

public void doZeroTimestampTest(int testNum, boolean expectSuccess, String connectString)
        throws IOException, SQLException {

    LOG.info("Beginning zero-timestamp test #" + testNum);

    try {//from  w  w w.  j  av  a2 s .  c o  m
        final String TABLE_NAME = "mysqlTimestampTable" + Integer.toString(testNum);

        // Create a table containing a full-zeros timestamp.
        SqoopOptions options = new SqoopOptions(connectString, TABLE_NAME);
        options.setUsername(AUTH_TEST_USER);
        options.setPassword(AUTH_TEST_PASS);

        manager = new DirectMySQLManager(options);

        Connection connection = null;
        Statement st = null;

        connection = manager.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, "
                + "ts TIMESTAMP NOT NULL)");

        st.executeUpdate("INSERT INTO " + TABLE_NAME + " VALUES(" + "NULL,'0000-00-00 00:00:00.0')");
        connection.commit();
        st.close();
        connection.close();

        // Run the import.
        String[] argv = getArgv(true, false, connectString, TABLE_NAME);
        try {
            runImport(argv);
        } catch (Exception e) {
            if (expectSuccess) {
                // This is unexpected. rethrow.
                throw new RuntimeException(e);
            } else {
                // We expected an error.
                LOG.info("Got exception running import (expected). msg: " + e);
            }
        }

        // Make sure the result file is there.
        Path warehousePath = new Path(this.getWarehouseDir());
        Path tablePath = new Path(warehousePath, TABLE_NAME);
        Path filePath = new Path(tablePath, "part-m-00000");

        File f = new File(filePath.toString());
        if (expectSuccess) {
            assertTrue("Could not find imported data file", f.exists());
            BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
            assertEquals("1,null", r.readLine());
            IOUtils.closeStream(r);
        } else {
            assertFalse("Imported data when expected failure", f.exists());
        }
    } finally {
        LOG.info("Finished zero timestamp test #" + testNum);
    }
}

From source file:dk.netarkivet.harvester.datamodel.GlobalCrawlerTrapListDBDAO.java

/**
 * Update a trap list. In order to update the trap expressions for this
 * list, we first delete all the existing trap expressions for the list
 * then add all those in the updated version.
 * @param trapList the trap list to update
 *///from  ww  w. j  a v  a 2s . c o  m
@Override
public void update(GlobalCrawlerTrapList trapList) {
    ArgumentNotValid.checkNotNull(trapList, "trapList");
    Connection conn = HarvestDBConnection.get();
    PreparedStatement stmt = null;
    try {
        conn.setAutoCommit(false);
        stmt = conn.prepareStatement(LIST_UPDATE_STMT);
        stmt.setString(1, trapList.getName());
        stmt.setString(2, trapList.getDescription());
        stmt.setBoolean(3, trapList.isActive());
        stmt.setInt(4, trapList.getId());
        stmt.executeUpdate();
        stmt.close();

        //Delete all the trap expressions.
        stmt = conn.prepareStatement(DELETE_EXPR_STMT);
        stmt.setInt(1, trapList.getId());
        stmt.executeUpdate();
        stmt.close();
        // Add the new trap expressions one by one.
        for (String expr : trapList.getTraps()) {
            stmt = conn.prepareStatement(INSERT_TRAP_EXPR_STMT);
            stmt.setInt(1, trapList.getId());
            stmt.setString(2, expr);
            stmt.executeUpdate();
            stmt.close();
        }
        conn.commit();
    } catch (SQLException e) {
        String message = "Error updating trap list :'" + trapList.getId() + "'\n"
                + ExceptionUtils.getSQLExceptionCause(e);
        log.warn(message, e);
        throw new UnknownID(message, e);
    } finally {
        DBUtils.closeStatementIfOpen(stmt);
        DBUtils.rollbackIfNeeded(conn, "update trap list", trapList);
        HarvestDBConnection.release(conn);
    }
}

From source file:com.slemarchand.sqlqueryscripting.scripting.sqlquery.SQLQueryExecutor.java

private List<List<Object>> _execQuery(String sqlQuery, int maxRows, List<String> columnLabels)
        throws SQLException {

    List<List<Object>> rows = null;

    Connection con = null;
    Statement stmt = null;//from www.j  a v  a2  s.  c o  m
    ResultSet rs = null;

    try {
        con = DataAccess.getConnection();

        con.setAutoCommit(false); // Prevent data updates

        stmt = con.createStatement();
        stmt.setMaxRows(maxRows);
        rs = stmt.executeQuery(sqlQuery);

        ResultSetMetaData md = rs.getMetaData();
        int cc = md.getColumnCount();

        rows = new ArrayList<List<Object>>(cc);

        columnLabels.clear();

        for (int c = 1; c <= cc; c++) {
            String cl = md.getColumnLabel(c);
            columnLabels.add(cl);
        }

        while (rs.next()) {
            List<Object> row = new ArrayList<Object>(cc);
            for (int c = 1; c <= cc; c++) {
                Object value = rs.getObject(c);
                row.add(value);
            }
            rows.add(row);
        }

    } finally {
        DataAccess.cleanUp(con, stmt, rs);
    }

    return rows;
}

From source file:dk.netarkivet.harvester.datamodel.GlobalCrawlerTrapListDBDAO.java

@Override
public int create(GlobalCrawlerTrapList trapList) {
    ArgumentNotValid.checkNotNull(trapList, "trapList");
    // Check for existence of a trapList in the database with the same name
    // and throw argumentNotValid if not
    if (exists(trapList.getName())) {
        throw new ArgumentNotValid(
                "Crawlertrap with name '" + trapList.getName() + "'already exists in database");
    }//from   ww w  .j av  a2 s.  co m
    int trapId;
    Connection conn = HarvestDBConnection.get();
    PreparedStatement stmt = null;
    try {
        conn.setAutoCommit(false);
        stmt = conn.prepareStatement(INSERT_TRAPLIST_STMT, Statement.RETURN_GENERATED_KEYS);
        stmt.setString(1, trapList.getName());
        stmt.setString(2, trapList.getDescription());
        stmt.setBoolean(3, trapList.isActive());
        stmt.executeUpdate();
        ResultSet rs = stmt.getGeneratedKeys();
        rs.next();
        trapId = rs.getInt(1);
        trapList.setId(trapId);
        for (String expr : trapList.getTraps()) {
            stmt = conn.prepareStatement(INSERT_TRAP_EXPR_STMT);
            stmt.setInt(1, trapId);
            stmt.setString(2, expr);
            stmt.executeUpdate();
        }
        conn.commit();
    } catch (SQLException e) {
        String message = "SQL error creating global crawler trap list \n"
                + ExceptionUtils.getSQLExceptionCause(e);
        log.warn(message, e);
        throw new IOFailure(message, e);
    } finally {
        DBUtils.closeStatementIfOpen(stmt);
        DBUtils.rollbackIfNeeded(conn, "create trap list", trapList);
        HarvestDBConnection.release(conn);
    }
    return trapId;
}

From source file:edu.clemson.cs.nestbed.server.adaptation.sql.ProgramSqlAdapter.java

public Program createNewProgram(int projectID, String name, String description) throws AdaptationException {
    Program program = null;/*  www . j a  va  2s.c o m*/
    Connection connection = null;
    Statement statement = null;
    ResultSet resultSet = null;

    try {
        connection = DriverManager.getConnection(CONN_STR);
        connection.setAutoCommit(false);
        statement = connection.createStatement();

        String query = "INSERT INTO Programs(projectID, name, " + "description, sourcePath) VALUES ( "
                + projectID + ", " + "'" + name + "', " + "'" + description + "', " + "'" + "[unknown]" + "')";

        log.debug("SQL Query:\n" + query);
        statement.executeUpdate(query);

        query = "SELECT * FROM Programs WHERE " + " projectID   =  " + projectID + "  AND " + " name        = '"
                + name + "' AND " + " description = '" + description + "'";

        resultSet = statement.executeQuery(query);

        if (!resultSet.next()) {
            connection.rollback();
            String msg = "Attempt to create program failed";
            log.error(msg);
            throw new AdaptationException(msg);
        }

        program = getProgram(resultSet);
        connection.commit();
    } catch (SQLException ex) {
        try {
            connection.rollback();
        } catch (Exception e) {
        }

        String msg = "SQLException in createNewProgram";
        log.error(msg, ex);
        throw new AdaptationException(msg, ex);
    } finally {
        try {
            resultSet.close();
        } catch (Exception ex) {
        }
        try {
            statement.close();
        } catch (Exception ex) {
        }
        try {
            connection.close();
        } catch (Exception ex) {
        }
    }

    return program;
}

From source file:cz.cas.lib.proarc.common.user.UserManagerSql.java

@Override
public void removePermissions(int groupId) {
    try {//from ww w .  java2s.  c o m
        Connection c = source.getConnection();
        boolean rollback = true;
        try {
            c.setAutoCommit(false);
            permissionStorage.remove(c, groupId);
            c.commit();
            rollback = false;
        } finally {
            DbUtils.close(c, rollback);
        }
    } catch (SQLException ex) {
        throw new IllegalStateException(ex);
    }
}

From source file:edu.caltechUcla.sselCassel.projects.jMarkets.server.data.DBConnector.java

/** Commit the current database transaction */
public void commit(Connection conn) throws SQLException {
    try {/*  w w  w .  j a  v  a  2 s. c o m*/
        conn.commit();
        conn.setAutoCommit(true);
    } catch (SQLException e) {
        throw e;
    }
}

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

@Override
public Comment getComment(int id) {
    Comment comment = null;//  w ww  .j a v a 2s . co m
    Connection conn = null;
    PreparedStatement stat = null;
    ResultSet res = null;
    try {
        conn = this.getConnection();
        conn.setAutoCommit(false);
        stat = conn.prepareStatement(LOAD_COMMENT);
        stat.setInt(1, id);
        res = stat.executeQuery();
        if (res.next()) {
            comment = this.popualteComment(res);
        }
    } catch (Throwable t) {
        _logger.error("Error load comment {}", id, t);
        throw new RuntimeException("Error load comment", t);
    } finally {
        closeDaoResources(res, stat, conn);
    }
    return comment;
}

From source file:cz.cas.lib.proarc.common.user.UserManagerSql.java

@Override
public void setPermissions(int groupId, Permission... permissions) {
    if (permissions == null || permissions.length == 0) {
        throw new IllegalStateException("permissions");
    }//w ww .  j  a  va  2s  . c  o m
    try {
        Connection c = source.getConnection();
        boolean rollback = true;
        try {
            c.setAutoCommit(false);
            permissionStorage.set(c, groupId, permissions);
            c.commit();
            rollback = false;
        } finally {
            DbUtils.close(c, rollback);
        }
    } catch (SQLException ex) {
        throw new IllegalStateException(ex);
    }
}

From source file:cz.cas.lib.proarc.common.user.UserManagerSql.java

@Override
public void setUserGroups(UserProfile user, List<Group> groups, String owner, String log) {
    try {// w  w w .j  a v  a2s.  c  o m
        FedoraTransaction ftx = new FedoraTransaction(remoteStorage);
        FedoraUserDao fedoraUsers = new FedoraUserDao();
        fedoraUsers.setTransaction(ftx);
        Connection c = source.getConnection();
        boolean rollback = true;
        try {
            c.setAutoCommit(false);
            groupStorage.removeMembership(c, user.getId());
            if (!groups.isEmpty()) {
                groupStorage.addMembership(c, user.getId(), groups);
            }
            fedoraUsers.setMembership(user, groups, log);
            c.commit();
            ftx.commit();
            rollback = false;
        } finally {
            ftx.close();
            DbUtils.close(c, rollback);
        }
    } catch (Exception ex) {
        throw new IllegalStateException(ex);
    }
}