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:de.unidue.inf.is.ezdl.dlservices.repository.store.repositories.DBRepository.java

@Override
protected void putAsIs(String oid, StoredDocument document) {
    Connection con = null;
    PreparedStatement st = null;//from   ww  w .j  a  va 2 s .  c  o  m
    PreparedStatement st2 = null;

    byte[] encoded = encode(document);
    ByteArrayInputStream is = new ByteArrayInputStream(encoded);

    String databaseIdForOid = databaseIdForOid(oid);

    try {
        con = provider.connection();

        st = con.prepareStatement(EXISTS);
        st.setString(1, databaseIdForOid);
        ResultSet rs = st.executeQuery();
        if (rs.next()) {
            String s = rs.getString(1);
            if (Boolean.valueOf(s)) {
                st2 = con.prepareStatement(UPDATE);
                st2.setBlob(1, is);
                st2.setString(2, databaseIdForOid);
                st2.execute();
            } else {
                getLogger().error("Error while checking if row exists");
            }
        } else {
            st2 = con.prepareStatement(PUT);
            st2.setString(1, databaseIdForOid);
            st2.setBlob(2, is);
            st2.execute();
        }
        con.commit();
    } catch (SQLException e) {
        rollback(con);
        getLogger().error("Error putting " + databaseIdForOid, e);
    } finally {
        ClosingUtils.close(st, st2);
        ClosingUtils.close(con);
    }
}

From source file:mx.com.pixup.portal.dao.ArtistaParserDaoJdbc.java

public void parserXML() {

    try {//from  w w w  .ja va 2 s. com

        //variables BD
        String sql = "INSERT INTO artista VALUES (?,?,?)";
        PreparedStatement preparedStatement;
        Connection connection = dataSource.getConnection();
        connection.setAutoCommit(false);

        //se obtiene elemento raiz
        Element artistas = this.xmlDocumento.getRootElement();
        //elementos 2do nivel
        List<Element> listaArtistas = artistas.getChildren();
        Iterator<Element> i = listaArtistas.iterator();

        while (i.hasNext()) {
            Element artista = i.next();

            //Elementos de tercer nivel
            Attribute id = artista.getAttribute("id");
            Element nombre = artista.getChild("nombre");
            Element descripcion = artista.getChild("descripcion");

            //construye parametros de la query
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1, id.getIntValue());
            preparedStatement.setString(2, nombre.getText());
            preparedStatement.setString(3, descripcion.getText());

            preparedStatement.execute();
        }

        //preparedStatement = connection.prepareStatement(sql);           
        // preparedStatement.setInt(1, valor);
        //  preparedStatement.execute();

        connection.commit();
    } catch (Exception e) {
        //*** se quit el return porque el mtodo es void
        System.out.println(e.getMessage());
    }

}

From source file:com.wso2telco.workflow.dao.WorkflowDbService.java

/**
 * Application entry.//w w  w. j a  va  2s  .  c  o  m
 *
 * @param applicationid the applicationid
 * @param operators     the operators
 * @return the integer
 * @throws Exception the exception
 */

public void applicationEntry(int applicationid, Integer[] operators) throws SQLException, BusinessException {

    Connection con = null;
    Statement st = null;

    try {
        con = DbUtils.getDbConnection(DataSourceNames.WSO2TELCO_DEP_DB);

        if (con == null) {
            throw new Exception("Connection not found");
        }
        con.setAutoCommit(false);
        st = con.createStatement();
        for (Integer d : operators) {
            if (!operatorAppsIsExist(applicationid, d)) {
                StringBuilder query = new StringBuilder();
                query.append("INSERT INTO operatorapps (applicationid,operatorid) ");
                query.append("VALUES (" + applicationid + "," + d + ")");
                st.addBatch(query.toString());
            }
        }
        st.executeBatch();
        con.commit();

    } catch (SQLException e) {
        throw new SQLException();
    } catch (Exception e) {
        throw new BusinessException(GenaralError.UNDEFINED);
    } finally {
        DbUtils.closeAllConnections(st, con, null);
    }

}

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

/**
 * Store frontier report data to the persistent storage.
 * @param report the report to store//  w w  w  .  ja v  a 2  s  .  c  om
 * @param filterId the id of the filter that produced the report
 * @param jobId The ID of the job responsible for this report
 * @return the update count
 */
public int storeFrontierReport(String filterId, InMemoryFrontierReport report, Long jobId) {
    ArgumentNotValid.checkNotNull(report, "report");
    ArgumentNotValid.checkNotNull(jobId, "jobId");

    Connection c = HarvestDBConnection.get();
    PreparedStatement stm = null;
    try {

        // First drop existing rows
        try {
            c.setAutoCommit(false);

            stm = c.prepareStatement("DELETE FROM frontierReportMonitor" + " WHERE jobId=? AND filterId=?");
            stm.setLong(1, jobId);
            stm.setString(2, filterId);

            stm.executeUpdate();

            c.commit();
        } catch (SQLException e) {
            String message = "SQL error dropping records for job ID " + jobId + " and filterId " + filterId
                    + "\n" + ExceptionUtils.getSQLExceptionCause(e);
            log.warn(message, e);
            return 0;
        } finally {
            DBUtils.closeStatementIfOpen(stm);
            DBUtils.rollbackIfNeeded(c, "storeFrontierReport delete", jobId);
        }

        // Now batch insert report lines
        try {
            c.setAutoCommit(false);

            stm = c.prepareStatement("INSERT INTO frontierReportMonitor(" + FR_COLUMN.getColumnsInOrder()
                    + ") VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");

            for (FrontierReportLine frl : report.getLines()) {
                stm.setLong(FR_COLUMN.jobId.rank(), jobId);
                stm.setString(FR_COLUMN.filterId.rank(), filterId);
                stm.setTimestamp(FR_COLUMN.tstamp.rank(), new Timestamp(report.getTimestamp()));
                stm.setString(FR_COLUMN.domainName.rank(), frl.getDomainName());
                stm.setLong(FR_COLUMN.currentSize.rank(), frl.getCurrentSize());
                stm.setLong(FR_COLUMN.totalEnqueues.rank(), frl.getTotalEnqueues());
                stm.setLong(FR_COLUMN.sessionBalance.rank(), frl.getSessionBalance());
                stm.setDouble(FR_COLUMN.lastCost.rank(), frl.getLastCost());
                stm.setDouble(FR_COLUMN.averageCost.rank(),
                        correctNumericIfIllegalAverageCost(frl.getAverageCost()));
                stm.setString(FR_COLUMN.lastDequeueTime.rank(), frl.getLastDequeueTime());
                stm.setString(FR_COLUMN.wakeTime.rank(), frl.getWakeTime());
                stm.setLong(FR_COLUMN.totalSpend.rank(), frl.getTotalSpend());
                stm.setLong(FR_COLUMN.totalBudget.rank(), frl.getTotalBudget());
                stm.setLong(FR_COLUMN.errorCount.rank(), frl.getErrorCount());

                // URIs are to be truncated to 1000 characters
                // (see SQL scripts)
                DBUtils.setStringMaxLength(stm, FR_COLUMN.lastPeekUri.rank(), frl.getLastPeekUri(),
                        MAX_URL_LENGTH, frl, "lastPeekUri");
                DBUtils.setStringMaxLength(stm, FR_COLUMN.lastQueuedUri.rank(), frl.getLastQueuedUri(),
                        MAX_URL_LENGTH, frl, "lastQueuedUri");

                stm.addBatch();
            }

            int[] updCounts = stm.executeBatch();
            int updCountTotal = 0;
            for (int count : updCounts) {
                updCountTotal += count;
            }

            c.commit();

            return updCountTotal;
        } catch (SQLException e) {
            String message = "SQL error writing records for job ID " + jobId + " and filterId " + filterId
                    + "\n" + ExceptionUtils.getSQLExceptionCause(e);
            log.warn(message, e);
            return 0;
        } finally {
            DBUtils.closeStatementIfOpen(stm);
            DBUtils.rollbackIfNeeded(c, "storeFrontierReport insert", jobId);
        }

    } finally {
        HarvestDBConnection.release(c);
    }
}

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

public ProgramProfilingSymbol createNewProfilingSymbol(int configID, int programSymbolID)
        throws AdaptationException {
    ProgramProfilingSymbol profilingSymbol = null;
    Connection connection = null;
    Statement statement = null;// w  ww  .ja  va  2 s.  c  om
    ResultSet resultSet = null;

    try {
        String query = "INSERT INTO ProgramProfilingSymbols"
                + "(projectDeploymentConfigurationID, programSymbolID)" + " VALUES (" + configID + ", "
                + programSymbolID + ")";

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

        query = "SELECT * FROM ProgramProfilingSymbols WHERE " + "projectDeploymentConfigurationID = "
                + configID + " AND programSymbolID             = " + programSymbolID;

        resultSet = statement.executeQuery(query);

        if (!resultSet.next()) {
            connection.rollback();
            String msg = "Attempt to create program profiling " + "symbol failed.";
            log.error(msg);
            throw new AdaptationException(msg);
        }
        profilingSymbol = getProfilingSymbol(resultSet);
        connection.commit();
    } catch (SQLException ex) {
        try {
            connection.rollback();
        } catch (Exception e) {
        }

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

From source file:dk.netarkivet.archive.arcrepositoryadmin.ReplicaCacheHelpers.java

/**
 * Method for updating an entry in the replicafileinfo table.
 * This method updates the 'checksum_checkdatetime'
 * and 'filelist_checkdatetime' with the given date argument.
 *
 * @param replicafileinfoGuid The guid to update.
 * @param checksum The new checksum for the entry.
 * @param date The date for the update.//  www.ja v a 2s . co m
 * @param state The status for the upload.
 * @param con An open connection to the archive database
 * @throws IOFailure If an error occurs in the connection to the database.
 */
protected static void updateReplicaFileInfo(long replicafileinfoGuid, String checksum, Date date,
        ReplicaStoreState state, Connection con) throws IOFailure {
    PreparedStatement statement = null;
    try {
        final String sql = "UPDATE replicafileinfo SET checksum = ?, "
                + "upload_status = ?, filelist_status = ?, "
                + "checksum_status = ?, checksum_checkdatetime = ?, "
                + "filelist_checkdatetime = ? WHERE replicafileinfo_guid = ?";

        FileListStatus fls;
        ChecksumStatus cs;

        if (state == ReplicaStoreState.UPLOAD_COMPLETED) {
            fls = FileListStatus.OK;
            cs = ChecksumStatus.OK;
        } else if (state == ReplicaStoreState.UPLOAD_FAILED) {
            fls = FileListStatus.MISSING;
            cs = ChecksumStatus.UNKNOWN;
        } else {
            fls = FileListStatus.NO_FILELIST_STATUS;
            cs = ChecksumStatus.UNKNOWN;
        }

        // complete the SQL statement.
        statement = DBUtils.prepareStatement(con, sql, checksum, state.ordinal(), fls.ordinal(), cs.ordinal(),
                date, date, replicafileinfoGuid);
        statement.executeUpdate();
        con.commit();
    } catch (Throwable e) {
        String errMsg = "Problems with updating a ReplicaFileInfo";
        log.warn(errMsg);
        throw new IOFailure(errMsg);
    } finally {
        DBUtils.closeStatementIfOpen(statement);
    }
}

From source file:hoot.services.db.DbUtils.java

public static void deleteOSMRecord(Connection conn, Long mapId) throws Exception {
    try {/*  w ww .jav  a 2s .  co  m*/
        deleteMapRelatedTablesByMapId(mapId);

        conn.setAutoCommit(false);
        Configuration configuration = getConfiguration();

        QMaps maps = QMaps.maps;
        new SQLDeleteClause(conn, configuration, maps).where(maps.id.eq(mapId)).execute();

        QReviewItems reviewItems = QReviewItems.reviewItems;
        new SQLDeleteClause(conn, configuration, reviewItems).where(reviewItems.mapId.eq(mapId)).execute();

        QElementIdMappings elementIdMappings = QElementIdMappings.elementIdMappings;
        new SQLDeleteClause(conn, configuration, elementIdMappings).where(elementIdMappings.mapId.eq(mapId))
                .execute();

        QReviewMap reviewMap = QReviewMap.reviewMap;
        new SQLDeleteClause(conn, configuration, reviewMap).where(reviewMap.mapId.eq(mapId)).execute();

        conn.commit();
    } catch (Exception e) {
        String msg = "Error deleting OSM record.  ";
        msg += "  " + e.getCause().getMessage();

        throw new Exception(msg);
    } finally {
        conn.setAutoCommit(true);
    }
}

From source file:com.mirth.connect.server.controllers.tests.TestUtils.java

public static void createTestMessagesFast(String channelId, Message templateMessage, int power)
        throws Exception {
    long localChannelId = ChannelController.getInstance().getLocalChannelId(channelId);
    deleteAllMessages(channelId);//ww w.  ja  va 2  s . c o m
    createTestMessages(channelId, templateMessage, 1);

    Connection connection = null;
    PreparedStatement messageStatement = null;
    PreparedStatement metaDataStatement = null;
    PreparedStatement contentStatement = null;
    long idOffset = templateMessage.getMessageId();

    logger.debug("Replicating messages in channel \"" + channelId + "\"");

    try {
        connection = getConnection();
        messageStatement = connection.prepareStatement("INSERT INTO d_m" + localChannelId
                + " (id, server_id, received_date, processed) SELECT id + ?, server_id, received_date, processed FROM d_m"
                + localChannelId);
        metaDataStatement = connection.prepareStatement("INSERT INTO d_mm" + localChannelId
                + " (id, server_id, message_id, chain_id, received_date, status, order_id) SELECT id, server_id, message_id + ?, chain_id, received_date, status, order_id FROM d_mm"
                + localChannelId);
        contentStatement = connection.prepareStatement("INSERT INTO d_mc" + localChannelId
                + " (metadata_id, message_id, content_type, content, is_encrypted, data_type) SELECT metadata_id, message_id + ?, content_type, content, is_encrypted, data_type FROM d_mc"
                + localChannelId);

        for (int i = 0; i < power; i++) {
            messageStatement.setLong(1, idOffset);
            metaDataStatement.setLong(1, idOffset);
            contentStatement.setLong(1, idOffset);

            messageStatement.executeUpdate();
            metaDataStatement.executeUpdate();
            contentStatement.executeUpdate();

            idOffset *= 2;

            connection.commit();
            logger.debug("# of messages in channel \"" + channelId + "\" is now " + getNumMessages(channelId));
        }
    } finally {
        close(messageStatement);
        close(metaDataStatement);
        close(contentStatement);
        close(connection);
    }

    fixMessageIdSequence(channelId);
    logger.debug("Finished replicating messages in channel \"" + channelId + "\"");
}

From source file:com.rosy.bill.dao.hibernate.SimpleHibernateDao.java

@SuppressWarnings("deprecation")
public String callProc(final String proc, final List<Object> paramList, final int outIndex, final int outType) {
    String result = null;//from ww  w . jav  a2  s . com
    java.sql.Connection conn = null;
    java.sql.CallableStatement cstmt = null;
    //Session session = this.getSession();
    try {

        conn = this.getSession().connection();
        conn.setAutoCommit(false);
        cstmt = conn.prepareCall(proc);
        for (int i = 0; paramList != null && i < paramList.size(); i++) {
            if (i + 1 == outIndex) {
                //cstmt.setInt(i + 1,
                //      (Integer.parseInt(paramList.get(i).toString())));
                cstmt.setString(i + 1, paramList.get(i).toString());
            } else {
                cstmt.setInt(i + 1, Integer.valueOf(paramList.get(i).toString()));
            }
        }
        cstmt.registerOutParameter(outIndex, outType);
        cstmt.execute();
        result = cstmt.getString(outIndex);
        conn.commit();
        //session.flush();
        //session.clear();
    } catch (Exception ex) {
        try {
            conn.rollback();
        } catch (SQLException e1) {
            logger.error("[" + proc + "]?" + e1.getMessage());
            e1.printStackTrace();
        }
        ex.printStackTrace();
    } finally {
        if (cstmt != null) {
            try {
                cstmt.close();
            } catch (Exception ex) {
            }
        }
    }
    return result;
}

From source file:com.aurel.track.screen.dashboard.bl.design.DashboardScreenDesignBL.java

public void checkAndCreateClientDefaultCockpit() {
    TDashboardScreenBean screen = null;/*from  w ww .ja  v  a  2 s .  c o m*/
    try {
        screen = (TDashboardScreenBean) DashboardScreenDesignBL.getInstance()
                .tryToLoadScreen(CLIENT_COCKPIT_TEMPLATE_ID);
        LOGGER.debug("Client default cockpit already exists.");
    } catch (Exception ex) {
        LOGGER.debug("Couldn't find client default cockpit, we are now going to create one.");
    }
    if (screen == null) {
        Connection cono = null;
        Statement ostmt = null;
        Locale locale = Locale.getDefault();
        LOGGER.debug("Using default locale:" + locale.getDisplayName());
        String templateName = "Client user default template";
        String description = "This template is assigned automatically to newly created client users";
        String templateLabel = "Client user default template";
        try {
            cono = InitDatabase.getConnection();
            ostmt = cono.createStatement();
            cono.setAutoCommit(false);
            String createClientDefaultTemplate = "INSERT INTO TDASHBOARDSCREEN (OBJECTID, NAME, LABEL, DESCRIPTION)"
                    + "VALUES (" + CLIENT_COCKPIT_TEMPLATE_ID + ",'" + templateName + "', '" + templateLabel
                    + "', '" + description + "')";
            ostmt.executeUpdate(createClientDefaultTemplate);
            cono.commit();
            cono.setAutoCommit(true);
            LOGGER.debug("Client user default cockpit screen has been created with ID: "
                    + CLIENT_COCKPIT_TEMPLATE_ID);
            createClientDefaultCockpit();
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
        } finally {
            if (ostmt != null) {
                try {
                    ostmt.close();
                } catch (SQLException e) {
                    LOGGER.warn(ExceptionUtils.getStackTrace(e));
                }
            }
            try {
                if (cono != null) {
                    cono.close();
                }
            } catch (Exception e) {
                LOGGER.info("Closing the connection failed with " + e.getMessage());
                LOGGER.warn(ExceptionUtils.getStackTrace(e));
            }
        }
    }
}