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.agiletec.plugins.jpstats.aps.system.services.stats.StatsDAO.java

@Override
public void deleteStatsRecord(Date from, Date to) {
    Connection conn = null;
    PreparedStatement prepStat = null;
    try {/*w  w  w.j  a  va2  s  .  co  m*/
        conn = this.getConnection();
        conn.setAutoCommit(false);
        prepStat = conn.prepareStatement(REMOVE_RECORDS);
        prepStat.setString(1, (new java.sql.Timestamp(from.getTime())).toString());
        prepStat.setString(2, (new java.sql.Timestamp(to.getTime())).toString());
        prepStat.executeUpdate();
        conn.commit();
    } catch (Throwable t) {
        _logger.error("Error removing statistic records", t);
        throw new RuntimeException("Error removing statistic records", t);
    } finally {
        closeDaoResources(null, prepStat, conn);
    }
}

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");
    }/* w w  w  .j ava2s  .c  o  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:com.saasovation.common.port.adapter.persistence.eventsourcing.mysql.MySQLJDBCEventStore.java

@Override
public EventStream eventStreamSince(EventStreamId anIdentity) {

    Connection connection = this.connection();

    ResultSet result = null;//from w w w.  j av a2  s.co m

    try {
        PreparedStatement statement = connection
                .prepareStatement("SELECT stream_version, event_type, event_body FROM tbl_es_event_store "
                        + "WHERE stream_name = ? AND stream_version >= ? " + "ORDER BY stream_version");

        statement.setString(1, anIdentity.streamName());
        statement.setInt(2, anIdentity.streamVersion());

        result = statement.executeQuery();

        EventStream eventStream = this.buildEventStream(result);

        if (eventStream.version() == 0) {
            throw new EventStoreException("There is no such event stream: " + anIdentity.streamName() + " : "
                    + anIdentity.streamVersion());
        }

        connection.commit();

        return eventStream;

    } catch (Throwable t) {
        throw new EventStoreException("Cannot query event stream for: " + anIdentity.streamName()
                + " since version: " + anIdentity.streamVersion() + " because: " + t.getMessage(), t);
    } finally {
        if (result != null) {
            try {
                result.close();
            } catch (SQLException e) {
                // ignore
            }
        }
        try {
            connection.close();
        } catch (SQLException e) {
            // ignore
        }
    }
}

From source file:localdomain.localhost.CasInitializer.java

@ManagedOperation
public void deleteUser(@NotNull String username) {
    Connection cnn = null;
    PreparedStatement stmt = null;
    try {//from  ww  w.  j  a v  a  2 s .  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:net.ageto.gyrex.persistence.carbonado.storage.internal.SchemaSupportJob.java

private IStatus processSchemas(final Collection<RepositoryContentType> contentTypes,
        final JDBCConnectionCapability jdbcConnectionCapability, final IProgressMonitor monitor)
        throws Exception {
    // spin the migration loop
    Connection connection = null;
    boolean wasAutoCommit = true; // default to auto-commit
    try {//from w ww. ja v a 2s  .c  o  m
        // get connection
        connection = jdbcConnectionCapability.getConnection();
        // remember auto-commit state
        wasAutoCommit = connection.getAutoCommit();

        // collect result
        final MultiStatus result = new MultiStatus(CarbonadoActivator.SYMBOLIC_NAME, 0, String.format(
                "Database schema verification result for database %s.", repository.getDescription()), null);

        // verify schemas
        final SubMonitor subMonitor = SubMonitor.convert(monitor, contentTypes.size());
        for (final RepositoryContentType contentType : contentTypes) {
            result.add(processSchema(contentType, connection, subMonitor.newChild(1)));
        }

        // commit any pending changes if migration was allowed
        if (commitWhenDone) {
            connection.commit();
        } else {
            connection.rollback();
        }

        return result;
    } finally {
        if (null != connection) {
            try {
                // verify that auto-commit state was not modified
                if (wasAutoCommit != connection.getAutoCommit()) {
                    // Carbonado uses auto-commit to detect if a transaction
                    // was in progress whan the connection was acquired previously
                    // in this case it does not close the connection, which is fine;
                    // however, if any schema-support implementation removed the auto-commit flag
                    // Carbonado will no longer close the connection because it thinks a
                    // transaction is in progress;
                    // thus we need to reset the auto-commit flag in this case!
                    LOG.debug(
                            "Resetting auto-commit flag on connection {} due to modifications during schema migration",
                            connection);
                    connection.setAutoCommit(wasAutoCommit);
                }
                jdbcConnectionCapability.yieldConnection(connection);
            } catch (final Exception e) {
                throw new IllegalStateException(
                        "Unable to properly return a database connection to the pool. This will lead to resource leaks! "
                                + e.getMessage(),
                        e);
            }
        }
    }
}

From source file:azkaban.trigger.JdbcTriggerLoader.java

private void updateTrigger(Connection connection, Trigger t, EncodingType encType)
        throws TriggerLoaderException {

    String json = JSONUtils.toJSON(t.toJson());
    byte[] data = null;
    try {/* www.j  a  v  a  2  s.  com*/
        byte[] stringData = json.getBytes("UTF-8");
        data = stringData;

        if (encType == EncodingType.GZIP) {
            data = GZIPUtils.gzipBytes(stringData);
        }
        logger.debug("NumChars: " + json.length() + " UTF-8:" + stringData.length + " Gzip:" + data.length);
    } catch (IOException e) {
        throw new TriggerLoaderException("Error encoding the trigger " + t.toString());
    }

    QueryRunner runner = new QueryRunner();

    try {
        int updates = runner.update(connection, UPDATE_TRIGGER, t.getSource(), t.getLastModifyTime(),
                encType.getNumVal(), data, t.getTriggerId());
        connection.commit();
        if (updates == 0) {
            throw new TriggerLoaderException("No trigger has been updated.");
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug("Updated " + updates + " records.");
            }
        }
    } catch (SQLException e) {
        logger.error(UPDATE_TRIGGER + " failed.");
        throw new TriggerLoaderException("Update trigger " + t.toString() + " into db failed. ", e);
    }
}

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

public Project createProject(int testbedID, String name, String description) throws AdaptationException {
    Project project = null;/*  ww  w . j a  va 2s . co m*/
    Connection connection = null;
    Statement statement = null;
    ResultSet resultSet = null;

    try {
        String query = "INSERT INTO Projects(testbedID, name, " + "description) VALUES (" + testbedID + ", '"
                + name + "', '" + description + "')";

        connection = DriverManager.getConnection(CONN_STR);
        statement = connection.createStatement();
        statement.executeUpdate(query);

        query = "SELECT * FROM Projects WHERE " + " testbedID   = " + testbedID + "  AND " + " name        = '"
                + name + "' AND " + " description = '" + description + "'";

        resultSet = statement.executeQuery(query);

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

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

        String msg = "SQLException in createProject";
        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 project;
}

From source file:edu.uga.cs.fluxbuster.db.PostgresDBInterface.java

/**
 * Executes a prepared statement with a result.
 * /*from   w  ww  . jav a  2 s.  co  m*/
 * @param con the connection to the database
 * @param stmt the prepared statement to execute
 * @return the result of the query
 */
private ResultSet executePreparedStatementWithResult(Connection con, PreparedStatement stmt) {
    ResultSet retval = null;
    try {
        con.setAutoCommit(false);
        retval = stmt.executeQuery();
        con.commit();
    } catch (SQLException e) {
        if (log.isErrorEnabled()) {
            log.error("", e);
        }
        if (con != null) {
            try {
                con.rollback();
            } catch (SQLException e1) {
                if (log.isErrorEnabled()) {
                    log.error("Error during rollback.", e1);
                }
            }
        }
    } finally {
        try {
            if (con != null && !con.isClosed()) {
                con.setAutoCommit(true);
            }
        } catch (SQLException e) {
            if (log.isErrorEnabled()) {
                log.error("Error setting auto commit.", e);
            }
        }
    }
    return retval;
}

From source file:com.netflix.metacat.usermetadata.mysql.MySqlLookupService.java

/**
 * Saves the lookup value./*from  w  ww . j  a va  2s  .c  om*/
 * @param name lookup name
 * @param values multiple values
 * @return returns the lookup with the given name.
 */
@Override
public Lookup setValues(final String name, final Set<String> values) {
    Lookup lookup = null;
    try {
        final Connection conn = getDataSource().getConnection();
        try {
            lookup = findOrCreateLookupByName(name, conn);
            Set<String> inserts = Sets.newHashSet();
            Set<String> deletes = Sets.newHashSet();
            final Set<String> lookupValues = lookup.getValues();
            if (lookupValues == null || lookupValues.isEmpty()) {
                inserts = values;
            } else {
                inserts = Sets.difference(values, lookupValues).immutableCopy();
                deletes = Sets.difference(lookupValues, values).immutableCopy();
            }
            lookup.setValues(values);
            if (!inserts.isEmpty()) {
                insertLookupValues(lookup.getId(), inserts, conn);
            }
            if (!deletes.isEmpty()) {
                deleteLookupValues(lookup.getId(), deletes, conn);
            }
            conn.commit();
        } catch (SQLException e) {
            conn.rollback();
            throw e;
        } finally {
            conn.close();
        }
    } catch (SQLException e) {
        final String message = String.format("Failed to set the lookup values for name %s", name);
        log.error(message, e);
        throw new UserMetadataServiceException(message, e);
    }
    return lookup;
}

From source file:com.skilrock.lms.web.scratchService.orderMgmt.common.RequestApproveAction.java

public String denyRetailer() throws LMSException {
    System.out.println("denie order for retailer");
    HttpSession session = getRequest().getSession();
    orderId = ((Integer) session.getAttribute("OrgId")).intValue();

    Connection conn = null;
    PreparedStatement pstmt1 = null;

    try {//  w w w.  ja v a  2  s.c o m
        conn = DBConnect.getConnection();
        conn.setAutoCommit(false);

        String query = QueryManager.getST5RetOrderRequest5Query();
        // String query = "update st_se_bo_order set order_status='DENIED'
        // WHERE order_id=?";
        pstmt1 = conn.prepareStatement(query);
        System.out.println("Query1 from Request Deny Action  " + query);
        System.out.println("OrderId>>>>" + orderId);
        pstmt1.setInt(1, orderId);
        pstmt1.executeUpdate();
        System.out.println(pstmt1);
        conn.commit();
        return SUCCESS;
    } catch (SQLException se) {
        System.out.println("We got an exception while preparing a statement:" + "Probably bad SQL.");
        se.printStackTrace();
        setRequestApproval("No");
        throw new LMSException(se);
    } finally {

        try {

            if (pstmt1 != null) {
                pstmt1.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException se) {
            throw new LMSException(se);
        }

    }

}