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.concursive.connect.web.modules.profile.dao.ProjectCategoryLogoFile.java

public boolean insert(Connection db) throws SQLException {
    boolean result = false;
    // The required linkModuleId
    linkModuleId = Constants.PROJECT_CATEGORY_FILES;
    // Determine if the database is in auto-commit mode
    boolean doCommit = false;
    try {/* w  ww.j a  v a2  s.  com*/
        if (doCommit = db.getAutoCommit()) {
            db.setAutoCommit(false);
        }
        // Insert the record
        result = super.insert(db);
        // Update the referenced pointer
        if (result) {
            int i = 0;
            PreparedStatement pst = db.prepareStatement(
                    "UPDATE lookup_project_category " + "SET logo_id = ? " + "WHERE code = ? ");
            pst.setInt(++i, id);
            pst.setInt(++i, linkItemId);
            int count = pst.executeUpdate();
            result = (count == 1);
        }
        if (doCommit) {
            db.commit();
        }
    } catch (Exception e) {
        if (doCommit) {
            db.rollback();
        }
        throw new SQLException(e.getMessage());
    } finally {
        if (doCommit) {
            db.setAutoCommit(true);
        }
    }
    return result;
}

From source file:mupomat.controller.ObradaKorisnik.java

@Override
public void obrisiPostojeci(Korisnik entitet) throws SQLException {
    try {/*from  w  w  w .java 2  s .co  m*/
        Connection veza = MySqlBazaPodataka.getConnection();

        veza.setAutoCommit(false);

        PreparedStatement izraz = veza.prepareStatement("delete from korisnik where sifra=?");

        izraz.setInt(1, entitet.getSifra());
        izraz.executeUpdate();

        izraz = veza.prepareStatement("delete from osoba  where oib=?");

        izraz.setString(1, entitet.getOib());
        izraz.executeUpdate();

        izraz.close();

        veza.commit();
        veza.close();
    } catch (ClassNotFoundException | IOException e) {
        //  System.out.println(e.getMessage());
        e.printStackTrace();

    }
}

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

@Override
public void deleteComment(int commentId) {
    Connection conn = null;
    PreparedStatement stat = null;
    try {//from  w ww  .  j  av a  2 s.co  m
        conn = this.getConnection();
        conn.setAutoCommit(false);
        ((RatingDAO) this.getRatingDAO()).removeRatingInTransaction(conn, commentId);
        stat = conn.prepareStatement(DELETE_COMMENT);
        stat.setInt(1, commentId);
        stat.executeUpdate();
        conn.commit();
    } catch (Throwable t) {
        this.executeRollback(conn);
        _logger.error("Error deleting a comment", t);
        throw new RuntimeException("Error deleting a comment", t);
    } finally {
        closeDaoResources(null, stat, conn);
    }
}

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  . j ava 2  s  . c  om
        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:com.agiletec.plugins.jpcontentfeedback.aps.system.services.contentfeedback.comment.CommentDAO.java

@Override
public void addComment(IComment comment) {
    Connection conn = null;
    PreparedStatement stat = null;
    try {/* w  w  w. ja  v  a2  s  .co  m*/
        conn = this.getConnection();
        conn.setAutoCommit(false);
        stat = conn.prepareStatement(ADD_COMMENT);
        stat.setInt(1, comment.getId());
        stat.setString(2, comment.getContentId());
        stat.setTimestamp(3, new Timestamp(new Date().getTime()));
        stat.setString(4, comment.getComment());
        stat.setInt(5, comment.getStatus());
        stat.setString(6, comment.getUsername());
        stat.executeUpdate();
        conn.commit();
    } catch (Throwable t) {
        this.executeRollback(conn);
        _logger.error("Error adding a comment", t);
        throw new RuntimeException("Error adding a comment", t);
    } finally {
        closeDaoResources(null, stat, conn);
    }

}

From source file:com.archivas.clienttools.arcutils.utils.database.PopulateDmDb.java

private void insertRows() throws SQLException, DatabaseException, JobException {
    ArcMoverEngine engine = LocalJvmArcMoverEngine.getInstance();

    List<ManagedJobSummary> allJobs = engine.getAllManagedJobs();
    JobId jobId = null;/*from  www . j a  v  a2 s  .  c o  m*/
    for (ManagedJobSummary summary : allJobs) {
        if (summary.getJobName().equals(jobName)) {
            jobId = summary.getJobId();
            break;
        }
    }
    if (jobId == null) {
        throw new IllegalArgumentException("Job \"" + jobName + "\" not found");
    }

    System.out.print("Loading managed job ....");
    System.out.flush();
    ManagedJobImpl jobImpl = engine.loadManagedJob(jobId, jobType);
    System.out.println(" done");

    ManagedJob job = jobImpl.getJob();
    AbstractProfileBase sourceProfile = job.getSourceProfile();
    AbstractProfileBase targetProfile = job.getTargetProfile();
    String sourcePath = job.getSourcePath();
    String targetPath = job.getTargetPath();

    ArcCopyFile file = generateFile(sourceProfile, targetProfile, sourcePath, targetPath);
    String fileSourcePath = file.getSourcePath();
    String fileSourceProfile = file.getSourceProfile().getName();
    String fileTargetPath = file.getTargetPath();
    String fileTargetProfile = (targetProfile == null ? null : file.getTargetProfile().getName());
    long fileSize = file.getSize();
    int fileObjectType = FileType.UNKNOWN.ordinal();
    if (file.isDirectory()) {
        fileObjectType = FileType.DIRECTORY.ordinal();
    } else if (file.isFile()) {
        fileObjectType = FileType.FILE.ordinal();
    }
    Long version = file.getSourceVersion();
    if (version == null) {
        version = 0L;
    }

    long recordId = jobImpl.getManagedJobSchema().getLastDbRecordId();
    long discoveredObjectCnt = jobImpl.getDiscoveredObjectCount();
    long totalObjCnt = jobImpl.getTotalObjectCount();

    System.out.println(
            "*** max RECORD_ID = " + recordId + ", initialDiscoveredObjectCnt = " + discoveredObjectCnt);

    boolean isDelete = (jobType == ManagedJob.Type.DELETE);
    String insertSql = "INSERT INTO " + ManagedJobSchema.getJobSchemaName(jobId.getId()) + "."
            + ManagedJobSchema.JOB_FILES_TABLE_NAME
            + (isDelete ? DELETE_INSERT_COLS_SQL : COPY_INSERT_COLS_SQL);
    String updateSql = "UPDATE " + ManagedJobsSchema.JOBS_TABLE_NAME + " set "
            + ManagedJobTableColumn.DISCOVERED_OBJ_CNT + " = ?, " + // 1
            ManagedJobTableColumn.MAX_RECORD_ID + " = ?, " + // 2
            ManagedJobTableColumn.TOTAL_OBJ_CNT + " = ? " + // 3
            " WHERE " + ManagedJobTableColumn.JOB_ID + " = ?"; // 4

    Connection conn = DatabaseResourceManager.createConnection();
    conn.setAutoCommit(false);
    PreparedStatement insertStatement = conn.prepareStatement(insertSql);
    PreparedStatement updateStatement = conn.prepareStatement(updateSql);

    startTime = System.currentTimeMillis();
    long l = 0;
    for (; l < rowCnt; l++) {
        recordId++;
        getLifeCycle(l);
        if (fileLifeCycle.ordinal() > FileLifeCycle.FINDING.ordinal()) {
            totalObjCnt++;
        }
        discoveredObjectCnt++;

        insertStatement.clearParameters();
        insertStatement.setInt(1, DatabaseResourceManager.boolToDbValue(false)); // initial list
        insertStatement.setLong(2, recordId); // record id

        insertStatement.setInt(3, fileObjectType); // record type
        insertStatement.setString(4, fileSourcePath); // source path
        insertStatement.setLong(5, version); // source version
        insertStatement.setString(6, fileSourceProfile); // source profile name
        insertStatement.setInt(7, fileLifeCycle.ordinal()); // life cycle
        if (fileStatus == null) {
            insertStatement.setNull(8, java.sql.Types.SMALLINT); // status
        } else {
            insertStatement.setInt(8, fileStatus.ordinal());
        }

        if (!isDelete) {
            insertStatement.setString(9, fileTargetPath); // target path
            insertStatement.setString(10, fileTargetProfile); // target profile name
            insertStatement.setLong(11, fileSize); // size
        }

        insertStatement.execute();
        if (l % 5000 == 0) {
            // update counts in jobs table
            updateStatement.clearParameters();
            updateStatement.setLong(1, discoveredObjectCnt);
            updateStatement.setLong(2, recordId);
            updateStatement.setLong(3, totalObjCnt);
            updateStatement.setLong(4, jobId.getId());
            updateStatement.execute();

            conn.commit();
            displayStats(l);
        }
    }

    updateStatement.clearParameters();
    updateStatement.setLong(1, discoveredObjectCnt);
    updateStatement.setLong(2, recordId);
    updateStatement.setLong(3, totalObjCnt);
    updateStatement.setLong(4, jobId.getId());
    updateStatement.execute();

    conn.commit();
    displayStats(l);
}

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

@Override
public void delete(int id) {
    Connection conn = HarvestDBConnection.get();
    PreparedStatement stmt = null;
    try {/* w ww  .  j av a2 s .  c om*/
        conn.setAutoCommit(false);
        // First delete the list.
        stmt = conn.prepareStatement(DELETE_TRAPLIST_STMT);
        stmt.setInt(1, id);
        stmt.executeUpdate();
        stmt.close();
        // Then delete all its expressions.
        stmt = conn.prepareStatement(DELETE_EXPR_STMT);
        stmt.setInt(1, id);
        stmt.executeUpdate();
        conn.commit();
    } catch (SQLException e) {
        String message = "Error deleting trap list: '" + id + "'\n" + ExceptionUtils.getSQLExceptionCause(e);
        log.warn(message, e);
        throw new UnknownID(message, e);
    } finally {
        DBUtils.closeStatementIfOpen(stmt);
        DBUtils.rollbackIfNeeded(conn, "delete trap list", id);
        HarvestDBConnection.release(conn);
    }
}

From source file:com.sf.springsecurityregistration1.core.repository.UserRepositoryJPA.java

private <T> void persistWithJDBC(T dto) throws SQLException {
    String table = dto.getClass().getAnnotation(javax.persistence.Table.class).name();
    //        System.out.println("table " + table);
    final String ROLE = "role";
    boolean isRole = table.toLowerCase().contains(ROLE);
    final String INSERT_USER = "INSERT INTO " + table + " (username, " + (isRole ? ROLE : "password")
            + ") VALUES (?, ?)";
    Connection connection = null;
    try {//from w w  w .j  av  a  2 s. co  m
        Properties connectionProps = new Properties();
        connectionProps.put("user", dbUsername);
        connectionProps.put("password", dbPassword);
        connection = DriverManager.getConnection(dbURL, connectionProps);
        connection.setAutoCommit(false);
        PreparedStatement insertUser = connection.prepareStatement(INSERT_USER);
        if (isRole) {
            UserRoles role = (UserRoles) dto;
            insertUser.setString(1, role.getUsername());
            insertUser.setString(2, role.getRole());
        } else {
            Users user = (Users) dto;
            insertUser.setString(1, user.getUsername());
            insertUser.setString(2, user.getPassword());
        }
        insertUser.execute();
        connection.commit();
    } finally {
        if (connection != null) {
            connection.close();
        }
    }
}

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

@Override
public List<Files> getAll() {
    Connection con = null;
    PreparedStatement statement = null;
    String sql = "select * from " + Files.FilesFieldsKey.TABLE;
    List<Files> listFStat = new ArrayList<>();
    try {/*w ww .  j a v  a  2s. c o  m*/
        con = DBConnector.getConnection();
        con.setAutoCommit(false);
        statement = con.prepareStatement(sql);
        ResultSet rs = statement.executeQuery();
        ResultSetToListFiles(rs, listFStat);
        con.commit();
    } catch (SQLException e) {
        handleException(e, con);
    } finally {
        doFinal(con, statement);
    }
    return listFStat;
}

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

@Override
public Files getFileById(Long id) {
    Connection con = null;
    PreparedStatement statement = null;
    String sql = "select * from " + Files.FilesFieldsKey.TABLE + " where id=?";
    Files fStat = new Files();
    try {//from  w  w w  .j ava2  s.co  m
        con = DBConnector.getConnection();
        con.setAutoCommit(false);
        statement = con.prepareStatement(sql);
        statement.setLong(1, id);
        ResultSet rs = statement.executeQuery();
        ResultSetToFiles(rs, fStat);
        con.commit();
    } catch (SQLException e) {
        handleException(e, con);
    } finally {
        doFinal(con, statement);
    }
    return fStat;
}