Example usage for java.sql PreparedStatement clearParameters

List of usage examples for java.sql PreparedStatement clearParameters

Introduction

In this page you can find the example usage for java.sql PreparedStatement clearParameters.

Prototype

void clearParameters() throws SQLException;

Source Link

Document

Clears the current parameter values immediately.

Usage

From source file:org.apache.hadoop.yarn.server.applicationhistoryservice.metrics.timeline.PhoenixHBaseAccessor.java

/**
 * Save Metric aggregate records.//from w  w  w.  j av a  2 s.c o m
 *
 * @throws SQLException
 */
public void saveClusterAggregateHourlyRecords(Map<TimelineClusterMetric, MetricHostAggregate> records,
        String tableName) throws SQLException {
    if (records == null || records.isEmpty()) {
        LOG.debug("Empty aggregate records.");
        return;
    }

    long start = System.currentTimeMillis();

    Connection conn = getConnection();
    PreparedStatement stmt = null;
    try {
        stmt = conn.prepareStatement(String.format(UPSERT_CLUSTER_AGGREGATE_TIME_SQL, tableName));
        int rowCount = 0;

        for (Map.Entry<TimelineClusterMetric, MetricHostAggregate> aggregateEntry : records.entrySet()) {
            TimelineClusterMetric clusterMetric = aggregateEntry.getKey();
            MetricHostAggregate aggregate = aggregateEntry.getValue();

            if (LOG.isTraceEnabled()) {
                LOG.trace("clusterMetric = " + clusterMetric + ", " + "aggregate = " + aggregate);
            }

            rowCount++;
            stmt.clearParameters();
            stmt.setString(1, clusterMetric.getMetricName());
            stmt.setString(2, clusterMetric.getAppId());
            stmt.setString(3, clusterMetric.getInstanceId());
            stmt.setLong(4, clusterMetric.getTimestamp());
            stmt.setString(5, clusterMetric.getType());
            stmt.setDouble(6, aggregate.getSum());
            //        stmt.setInt(7, aggregate.getNumberOfHosts());
            stmt.setLong(7, aggregate.getNumberOfSamples());
            stmt.setDouble(8, aggregate.getMax());
            stmt.setDouble(9, aggregate.getMin());

            try {
                stmt.executeUpdate();
            } catch (SQLException sql) {
                // we have no way to verify it works!!!
                LOG.error(sql);
            }

            if (rowCount >= PHOENIX_MAX_MUTATION_STATE_SIZE - 1) {
                conn.commit();
                rowCount = 0;
            }
        }

        conn.commit();

    } finally {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                // Ignore
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException sql) {
                // Ignore
            }
        }
    }
    long end = System.currentTimeMillis();
    if ((end - start) > 60000l) {
        LOG.info("Time to save: " + (end - start) + ", " + "thread = " + Thread.currentThread().getName());
    }
}

From source file:com.commander4j.db.JDBPrinters.java

public boolean update() {
    boolean result = false;
    try {//from w  w w. j a  v a  2 s. c  o  m
        PreparedStatement stmtupdate;
        stmtupdate = Common.hostList.getHost(getHostID()).getConnection(getSessionID()).prepareStatement(
                Common.hostList.getHost(getHostID()).getSqlstatements().getSQL("JDBPrinters.update"));

        stmtupdate.setString(1, getPrinterType());
        stmtupdate.setString(2, getEnabled());
        stmtupdate.setString(3, getIPAddress());
        stmtupdate.setString(4, getPort());
        stmtupdate.setString(5, getDescription());
        stmtupdate.setString(6, getLanguage());
        stmtupdate.setString(7, getDPI());
        stmtupdate.setString(8, getEnableExport());
        stmtupdate.setString(9, getExportPath());
        stmtupdate.setString(10, getEnableDirectPrint());
        stmtupdate.setString(11, getExportFormat());
        stmtupdate.setString(12, getPaperSize());
        stmtupdate.setString(13, getPrinterID());
        stmtupdate.setString(14, getGroupID());
        stmtupdate.execute();
        stmtupdate.clearParameters();
        if (Common.hostList.getHost(getHostID()).getConnection(getSessionID()).getAutoCommit() == false) {
            Common.hostList.getHost(getHostID()).getConnection(getSessionID()).commit();
        }
        stmtupdate.close();
        result = true;
    } catch (Exception e) {
        setErrorMessage(e.getMessage());
        result = false;
    }
    return result;
}

From source file:org.sakaiproject.search.journal.impl.JournaledFSIndexStorage.java

/**
 * Since this is a singleton, we can cache the savePoint only updating on
 * change. The Save Point is the number of the journal entry that this node
 * has merged upto and including//from   w  ww.  ja va 2s  . com
 * 
 * @see org.sakaiproject.search.maintanence.impl.JournaledObject#getJounalSavePoint()
 */
public long getJournalSavePoint() {
    if (journalSavePoint == -1) {
        Connection connection = null;
        PreparedStatement getJournalSavePointPst = null;
        ResultSet rs = null;
        try {
            connection = datasource.getConnection();
            getJournalSavePointPst = connection
                    .prepareStatement("select jid from search_node_status where serverid = ? ");
            getJournalSavePointPst.clearParameters();
            getJournalSavePointPst.setString(1, serverId);
            rs = getJournalSavePointPst.executeQuery();
            if (rs.next()) {
                journalSavePoint = rs.getLong(1);
                lastUpdate = System.currentTimeMillis();
            }

        } catch (Exception ex) {
            log.warn("Unable to get Search Jorunal SavePoint ", ex);
        } finally {
            try {
                rs.close();
            } catch (Exception ex) {
                log.debug(ex);
            }
            try {
                getJournalSavePointPst.close();
            } catch (Exception ex) {
                log.debug(ex);
            }
            try {
                connection.close();
            } catch (Exception ex) {
                log.debug(ex);
            }

        }
    }
    return journalSavePoint;
}

From source file:org.apache.jackrabbit.core.persistence.bundle.BundleDbPersistenceManager.java

/**
 * Resets the given <code>PreparedStatement</code> by clearing the
 * parameters and warnings contained.//from   ww w. j  a  v  a 2s . c o m
 *
 * @param stmt The <code>PreparedStatement</code> to reset. If
 *             <code>null</code> this method does nothing.
 */
protected synchronized void resetStatement(PreparedStatement stmt) {
    if (stmt != null) {
        try {
            stmt.clearParameters();
            stmt.clearWarnings();
        } catch (SQLException se) {
            logException("Failed resetting PreparedStatement", se);
        }
    }
}

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

public void markFilesReadyToProcess(Collection<ArcProcessFile> filesReadyToProcess) throws DatabaseException {
    synchronized (DatabaseResourceManager.DB_LOCK) {
        PooledDbConnection conn = null;/*  ww  w  .  j  av a2  s  .c om*/
        try {
            conn = connPool.getConnection();
            conn.setAutoCommit(false);
            PreparedStatement stmt = conn.prepareStatement(MARK_FILES_READY_TO_PROCESS_STMT_NAME,
                    markFilesReadyToProcessSql);
            long sizeToAdd = 0;
            for (ArcProcessFile file : filesReadyToProcess) {
                long fileSize = file.getSourceFile().getSize();
                sizeToAdd += fileSize;
                stmt.clearParameters();
                stmt.setLong(1, fileSize);
                stmt.setLong(2, file.getDatabaseRecordId());
                stmt.addBatch();
            }
            stmt.executeBatch();

            // now update overall job stats to reflect these changes
            ManagedJobsSchema.getInstance().updateTotalFilesStats(conn, jobId, filesReadyToProcess.size(),
                    sizeToAdd);

            conn.commit();
        } catch (Exception e) {
            rollback(conn);
            throw new DatabaseException(
                    DBUtils.getErrorMessage("An error occurred marking files ready to process", e), e);
        } finally {
            connPool.returnConnection(conn);
        }
    }
}

From source file:org.jasig.portal.groups.RDBMEntityGroupStore.java

public boolean containsGroupNamed(IEntityGroup containingGroup, String memberName) throws GroupsException {
    String groupKey = containingGroup.getLocalKey();
    String service = containingGroup.getServiceName().toString();

    Connection conn = RDBMServices.getConnection();
    try {/* www .j  av a2 s.c  o m*/
        String sql = getCountMemberGroupsNamedSql();
        PreparedStatement ps = conn.prepareStatement(sql);
        try {
            ps.clearParameters();
            ps.setString(1, groupKey);
            ps.setString(2, memberName);
            ps.setString(3, service);
            if (log.isDebugEnabled())
                log.debug("RDBMEntityGroupStore.containsGroupNamed(): " + ps + " (" + groupKey + ", "
                        + memberName + ", " + service + ")");
            ResultSet rs = ps.executeQuery();
            try {
                return (rs.next()) && (rs.getInt(1) > 0);
            } finally {
                rs.close();
            }
        } finally {
            ps.close();
        }
    } catch (Exception e) {
        log.error("RDBMEntityGroupStore.containsGroup(): " + e);
        throw new GroupsException("Problem retrieving data from store: " + e);
    } finally {
        RDBMServices.releaseConnection(conn);
    }
}

From source file:org.sakaiproject.search.indexer.impl.SearchBuilderQueueManager.java

/**
 * @param runtimeToDo//from ww  w.  j  a v a 2 s .  com
 * @param connection
 * @return
 * @throws SQLException
 */
private void commitPendingAndUnLock(List<SearchBuilderItem> runtimeToDo, Connection connection)
        throws SQLException {
    PreparedStatement unLockPst = null;
    PreparedStatement deletePst = null;
    try {
        unLockPst = connection.prepareStatement("update " //$NON-NLS-1$
                + SEARCH_BUILDER_ITEM_T + " set searchstate = ? " //$NON-NLS-1$
                + " where id = ?  and  searchstate = ? "); //$NON-NLS-1$

        deletePst = connection.prepareStatement(" delete from " //$NON-NLS-1$
                + SEARCH_BUILDER_ITEM_T + " where id = ? "); //$NON-NLS-1$

        for (Iterator<SearchBuilderItem> isbi = runtimeToDo.iterator(); isbi.hasNext();) {

            SearchBuilderItem sbi = isbi.next();

            if (SearchBuilderItem.ACTION_DELETE.equals(sbi.getSearchaction())) {
                deletePst.clearParameters();
                deletePst.setString(1, sbi.getId());
                if (deletePst.executeUpdate() != 1) {
                    log.warn("Failed to delete " + sbi.getName() + "  ");
                } else {
                    log.debug("Delete " + sbi.getName() + "  ");

                }
                connection.commit();
            } else {
                unLockPst.clearParameters();
                unLockPst.setInt(1, SearchBuilderItem.STATE_COMPLETED.intValue());
                unLockPst.setString(2, sbi.getId());
                unLockPst.setInt(3, sbi.getLock());
                if (unLockPst.executeUpdate() != 1) {
                    log.warn("Failed to mark " + sbi + " as completed ");
                } else {
                    log.debug("Marked " + sbi.getName() + " as completed ");
                }
                sbi.setSearchstate(SearchBuilderItem.STATE_COMPLETED);
                connection.commit();
            }
        }
    } finally {
        try {
            unLockPst.close();
        } catch (Exception ex) {
            log.warn("Error unlocking pst", ex);
        }
        try {
            deletePst.close();
        } catch (Exception ex) {
            log.warn("Error deleting pst", ex);
        }
    }
}

From source file:org.sakaiproject.search.indexer.impl.test.TDataSource.java

public List<SearchBuilderItem> populateDocuments(long targetItems, String prefix) throws SQLException {
    int nitems = 0;

    Connection connection = null;
    PreparedStatement insertPST = null;
    List<SearchBuilderItem> items = new ArrayList<SearchBuilderItem>();
    try {//  ww w  .  j  a  v  a2 s  .com
        connection = getDataSource().getConnection();
        insertPST = connection.prepareStatement("insert into searchbuilderitem "
                + "(id,version,name,context,searchaction,searchstate,itemscope) values " + "(?,?,?,?,?,?,?)");
        for (int i = 0; i < targetItems; i++) {
            int state = i % SearchBuilderItem.states.length;
            String name = SearchBuilderItem.states[state];
            int action = i % 3;
            if (state == SearchBuilderItem.STATE_PENDING && action == SearchBuilderItem.ACTION_ADD) {
                nitems++;
            }
            SearchBuilderItemImpl sbi = new SearchBuilderItemImpl();
            sbi.setContext("/" + name + prefix + "/at/a");
            sbi.setName("/" + name + prefix + "/at/a/location/" + i);
            sbi.setVersion(new Date(System.currentTimeMillis()));
            sbi.setId(String.valueOf(System.currentTimeMillis()) + String.valueOf(i));
            sbi.setItemscope(SearchBuilderItem.ITEM);
            sbi.setSearchaction(action);
            sbi.setSearchstate(state);

            insertPST.clearParameters();
            insertPST.setString(1, sbi.getId());
            insertPST.setTimestamp(2, new Timestamp(sbi.getVersion().getTime()));
            insertPST.setString(3, sbi.getName());
            insertPST.setString(4, sbi.getContext());
            insertPST.setInt(5, sbi.getSearchaction());
            insertPST.setInt(6, sbi.getSearchstate());
            insertPST.setInt(7, sbi.getItemscope());
            insertPST.execute();

            items.add(sbi);
        }
        connection.commit();
    } finally {
        try {
            insertPST.close();
        } catch (Exception ex2) {
            log.debug(ex2);
        }
        try {
            connection.close();
        } catch (Exception ex2) {
            log.debug(ex2);
        }
    }
    return items;

}

From source file:org.wso2.carbon.registry.core.jdbc.dao.JDBCLogsDAO.java

private void addLogRecords(LogRecord[] logRecords, JDBCDataAccessManager dataAccessManager)
        throws RegistryException {
    PreparedStatement s = null;
    Connection conn = null;/*ww  w  .  ja  v a 2  s.  c  o  m*/
    try {
        conn = dataAccessManager.getDataSource().getConnection();
        if (conn.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) {
            conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        }
        conn.setAutoCommit(false);
        String sql = "INSERT INTO REG_LOG (REG_PATH, REG_USER_ID, REG_LOGGED_TIME, "
                + "REG_ACTION, REG_ACTION_DATA, REG_TENANT_ID) " + "VALUES (?, ?, ?, ?, ?, ?)";

        s = conn.prepareStatement(sql);
        for (LogRecord logRecord : logRecords) {
            s.clearParameters();
            s.setString(1, logRecord.getResourcePath());
            s.setString(2, logRecord.getUserName());
            s.setTimestamp(3, new Timestamp(logRecord.getTimestamp().getTime()));
            s.setInt(4, logRecord.getAction());
            s.setString(5, logRecord.getActionData());
            s.setInt(6, logRecord.getTenantId());
            s.addBatch();
        }
        int[] status = s.executeBatch();
        if (log.isDebugEnabled()) {
            log.debug("Successfully added " + status.length + " log records.");
        }
        conn.commit();

    } catch (SQLException e) {
        try {
            if (conn != null) {
                conn.rollback();
            }
        } catch (SQLException e1) {
            log.error("Failed to rollback log insertion.", e);
        }
        String msg = "Failed to update log batch records " + ". " + e.getMessage();
        log.error(msg, e);
        throw new RegistryException(msg, e);
    } finally {
        try {
            if (s != null) {
                s.close();
            }
            if (conn != null && !(conn.isClosed())) {
                conn.close();
            }
        } catch (SQLException ex) {
            String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
            log.error(msg, ex);
        }
    }
}

From source file:org.sakaiproject.search.journal.impl.JournaledFSIndexStorage.java

public void setJournalIndexEntry(long journalEntry) {
    if (journalSavePoint != journalEntry) {
        Connection connection = null;
        PreparedStatement updateJournalSavePointPst = null;
        PreparedStatement insertJournalSavePointPst = null;
        try {/*from ww  w  . j  a v a 2s. com*/
            connection = datasource.getConnection();
            updateJournalSavePointPst = connection
                    .prepareStatement("update search_node_status set jid = ?, jidts = ? where  serverid = ? ");
            updateJournalSavePointPst.clearParameters();
            updateJournalSavePointPst.setLong(1, journalEntry);
            updateJournalSavePointPst.setLong(2, System.currentTimeMillis());
            updateJournalSavePointPst.setString(3, serverId);
            if (updateJournalSavePointPst.executeUpdate() != 1) {
                insertJournalSavePointPst = connection.prepareStatement(
                        "insert into  search_node_status (jid,jidts,serverid) values (?,?,?) ");
                insertJournalSavePointPst.clearParameters();
                insertJournalSavePointPst.setLong(1, journalEntry);
                insertJournalSavePointPst.setLong(2, System.currentTimeMillis());
                insertJournalSavePointPst.setString(3, serverId);
                if (insertJournalSavePointPst.executeUpdate() != 1) {
                    throw new SQLException("Unable to update journal entry for some reason ");
                }
            }
            connection.commit();
            journalSavePoint = journalEntry;

        } catch (Exception ex) {
            try {
                if (connection != null) {
                    connection.rollback();
                }
            } catch (Exception ex2) {
                log.debug(ex);
            }
            log.warn("Unable to get Search Jorunal SavePoint ", ex);
        } finally {
            try {
                if (updateJournalSavePointPst != null)
                    updateJournalSavePointPst.close();
            } catch (Exception ex) {
                log.debug(ex);
            }
            try {
                if (insertJournalSavePointPst != null)
                    insertJournalSavePointPst.close();
            } catch (Exception ex) {
                log.debug(ex);
            }
            try {
                if (connection != null)
                    connection.close();
            } catch (Exception ex) {
                log.debug(ex);
            }

        }
    }
}