Example usage for java.sql PreparedStatement setLong

List of usage examples for java.sql PreparedStatement setLong

Introduction

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

Prototype

void setLong(int parameterIndex, long x) throws SQLException;

Source Link

Document

Sets the designated parameter to the given Java long value.

Usage

From source file:data.DefaultExchanger.java

protected void setNullableLong(PreparedStatement ps, short index, JsonNode node, String column)
        throws SQLException {
    if (node.get(column).isNull()) {
        ps.setNull(index, Types.BIGINT);
    } else {//from ww w.  jav  a2s . co m
        ps.setLong(index, node.get(column).longValue());
    }
}

From source file:com.chenxin.authority.common.logback.DBAppender.java

@SuppressWarnings("rawtypes")
protected void insertProperties(Map<String, String> mergedMap, Connection connection, long eventId)
        throws SQLException {
    Set propertiesKeys = mergedMap.keySet();
    // TODO:add chenxin ?logging_event_property
    if (propertiesKeys.size() < -1) {
        PreparedStatement insertPropertiesStatement = connection.prepareStatement(insertPropertiesSQL);

        for (Iterator i = propertiesKeys.iterator(); i.hasNext();) {
            String key = (String) i.next();
            String value = mergedMap.get(key);

            insertPropertiesStatement.setLong(1, eventId);
            insertPropertiesStatement.setString(2, key);
            insertPropertiesStatement.setString(3, value);

            if (cnxSupportsBatchUpdates) {
                insertPropertiesStatement.addBatch();
            } else {
                insertPropertiesStatement.execute();
            }/* w w  w. ja  v a  2s .  co m*/
        }

        if (cnxSupportsBatchUpdates) {
            insertPropertiesStatement.executeBatch();
        }

        insertPropertiesStatement.close();
        insertPropertiesStatement = null;
    }
}

From source file:org.miloss.fgsms.services.rs.impl.reports.AvailabilityByService.java

private List<StatusRecordsExt> getStatusRecords(String url, TimeRange range, Connection con) {
    List<StatusRecordsExt> ret = new ArrayList<StatusRecordsExt>();
    //first get the record just before the start of the range, if it exists
    PreparedStatement com = null;
    ResultSet rs = null;/* ww  w  .j a v a 2s.c om*/
    try {
        com = con.prepareStatement(
                "select status from availability where uri=? and  utcdatetime < ? order by utcdatetime desc limit 1;");
        com.setString(1, url);
        com.setLong(2, range.getStart().getTimeInMillis());
        rs = com.executeQuery();
        if (rs.next()) {
            //add a record for the exact start time of the range
            StatusRecordsExt x = new StatusRecordsExt();
            x.gcal = new GregorianCalendar();
            x.gcal.setTimeInMillis(range.getStart().getTimeInMillis());
            x.status = rs.getBoolean("status");
            ret.add(x);
        }
    } catch (Exception ex) {
        log.log(Level.WARN, null, ex);
    } finally {
        DBUtils.safeClose(rs);
        DBUtils.safeClose(com);
    }
    try {
        //get everything within the range
        com = con.prepareStatement(
                "select * from availability where uri=? and  utcdatetime >= ?  and utcdatetime <=? order by utcdatetime asc;");
        com.setString(1, url);
        com.setLong(2, range.getStart().getTimeInMillis());
        com.setLong(3, range.getEnd().getTimeInMillis());
        rs = com.executeQuery();
        boolean lastStatus = true;
        while (rs.next()) {
            //in order to produce a square wave style chart, inject an additional point for this time-1 for the same status
            //as the previous item
            if (!ret.isEmpty()) {
                StatusRecordsExt get = ret.get(ret.size() - 1);
                StatusRecordsExt x = new StatusRecordsExt();
                x.gcal = new GregorianCalendar();
                x.gcal.setTimeInMillis(rs.getLong("utcdatetime") - 1);
                x.status = get.status;
                ret.add(x);
            }
            StatusRecordsExt x = new StatusRecordsExt();
            x.gcal = new GregorianCalendar();
            x.gcal.setTimeInMillis(rs.getLong("utcdatetime"));
            x.status = rs.getBoolean("status");
            lastStatus = x.status;
            ret.add(x);
        }

        StatusRecordsExt x = new StatusRecordsExt();
        x.gcal = new GregorianCalendar();
        x.gcal.setTimeInMillis(range.getEnd().getTimeInMillis());
        x.status = lastStatus;
        ret.add(x);

        //getting the next record isn't important in this case as we are only interested in data within the range.
        return ret;
    } catch (Exception ex) {

        log.log(Level.WARN, null, ex);
    } finally {
        DBUtils.safeClose(rs);
        DBUtils.safeClose(com);
    }
    return null;
}

From source file:com.flexive.ejb.beans.workflow.RouteEngineBean.java

/**
 * Deletes a route defined by its unique id.
 *
 * @param routeId   the route id//from  w  w  w. java2  s .c  om
 * @throws FxApplicationException if an error occured
 */
private void deleteRoute(long routeId) throws FxApplicationException {

    // Create the new step
    Connection con = null;
    PreparedStatement stmt = null;
    final String sql = "DELETE FROM " + TBL_WORKFLOW_ROUTES + " WHERE ID=?";
    boolean success = false;
    try {
        // Obtain a database connection
        con = Database.getDbConnection();

        // Create the new workflow instance
        stmt = con.prepareStatement(sql);
        stmt.setLong(1, routeId);
        stmt.executeUpdate();
        success = true;
    } catch (SQLException exc) {
        throw new FxRemoveException(LOG, "ex.routes.delete", exc, routeId, exc.getMessage());
    } finally {
        Database.closeObjects(RouteEngineBean.class, con, stmt);
        if (!success) {
            EJBUtils.rollback(ctx);
        } else {
            StructureLoader.reloadWorkflows(FxContext.get().getDivisionId());
        }
    }
}

From source file:com.splicemachine.mrio.api.core.SMSQLUtil.java

public void commitChildTransaction(Connection conn, long childTxnID) throws SQLException {
    PreparedStatement ps = conn.prepareStatement("call SYSCS_UTIL.SYSCS_COMMIT_CHILD_TRANSACTION(?)");
    ps.setLong(1, childTxnID);
    ps.execute();//from   ww w  . j  a v  a  2s . c  om
}

From source file:dao.DirImageAddQuery.java

/**
* This method is used to add blobstreams for directory.
* @param conn - the connection/* w  w w .  ja va  2s .c  o m*/
* @param blobType - the blob type (1 - photos, 2-music, 3-video 4 - documents, 5 - archives)
* @param mimeType - the mime type (image/jpeg, application/octet-stream)
* @param btitle - the title for this blob
* @param bsize - the size of the blob
* @param zoom - the zoom for the blob (used for displaying for image/jpeg)
* @param directoryId - the directoryId
* @param loginId - the loginId
* @param caption - the caption
* @throws Dao Exception - when an error or exception occurs while inserting this blob in DB.
*
 **/
public void run(Connection conn, String entryid, int blobType, String mimeType, String btitle, long bsize,
        int zoom, String directoryId, String loginId, String caption, boolean convertEntryId)
        throws BaseDaoException {

    byte[] capBytes = { ' ' };
    if (!RegexStrUtil.isNull(caption)) {
        capBytes = caption.getBytes();
    }

    PreparedStatement s = null;
    String stmt = null;
    if (convertEntryId) {
        stmt = "insert into dirimages values(?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP(), ?, ?, ?)";
    } else {
        stmt = "insert into dirimages values(?, " + "LAST_INSERT_ID()"
                + ", ?, ?, ?, ?, ?, CURRENT_TIMESTAMP(), ?, ?, ?)";
    }
    try {
        s = conn.prepareStatement(stmt);
        if (convertEntryId) {
            s.setLong(1, 0);
            s.setLong(2, new Long(entryid));
            s.setLong(3, new Long(directoryId));
            s.setLong(4, new Long(loginId));
            s.setInt(5, new Integer(blobType));
            s.setString(6, mimeType);
            s.setString(7, btitle);
            s.setLong(8, bsize);
            s.setInt(9, new Integer(zoom));
            s.setBytes(10, capBytes);
        } else {
            s.setLong(1, 0);
            s.setLong(2, new Long(directoryId));
            s.setLong(3, new Long(loginId));
            s.setInt(4, new Integer(blobType));
            s.setString(5, mimeType);
            s.setString(6, btitle);
            s.setLong(7, bsize);
            s.setInt(8, new Integer(zoom));
            s.setBytes(9, capBytes);
        }
        s.executeUpdate();
    } catch (Exception e) {
        throw new BaseDaoException("Error inserting into dirimages query, " + stmt, e);
    }
}

From source file:net.solarnetwork.node.dao.jdbc.consumption.JdbcConsumptionDatumDao.java

@Override
protected void setStoreStatementValues(ConsumptionDatum datum, PreparedStatement ps) throws SQLException {
    int col = 1;// w w  w . j  ava 2  s. com
    ps.setTimestamp(col++, new java.sql.Timestamp(
            datum.getCreated() == null ? System.currentTimeMillis() : datum.getCreated().getTime()));
    ps.setString(col++, datum.getSourceId() == null ? "" : datum.getSourceId());
    if (datum.getLocationId() == null) {
        ps.setNull(col++, Types.BIGINT);
    } else {
        ps.setLong(col++, datum.getLocationId());
    }
    if (datum.getWatts() == null) {
        ps.setNull(col++, Types.INTEGER);
    } else {
        ps.setInt(col++, datum.getWatts());
    }
    if (datum.getWattHourReading() == null) {
        ps.setNull(col++, Types.BIGINT);
    } else {
        ps.setLong(col++, datum.getWattHourReading());
    }
}

From source file:at.alladin.rmbt.statisticServer.OpenTestSearchResource.java

/**
 * Fills in the given fields in the queue into the given prepared statement
 * @param ps/* www  .j  a  v a 2 s  . c  o m*/
 * @param searchValues
 * @param firstField
 * @return
 * @throws SQLException
 */
private static PreparedStatement fillInWhereClause(PreparedStatement ps,
        Queue<Map.Entry<String, FieldType>> searchValues, int firstField) throws SQLException {
    //insert all values in the prepared statement in the order
    //in which the values had been put in the queue
    for (Map.Entry<String, FieldType> entry : searchValues) {
        switch (entry.getValue()) {
        case STRING:
            ps.setString(firstField, entry.getKey());
            break;
        case DATE:
            ps.setTimestamp(firstField, new Timestamp(Long.parseLong(entry.getKey())));
            break;
        case LONG:
            ps.setLong(firstField, Long.parseLong(entry.getKey()));
            break;
        case DOUBLE:
            ps.setDouble(firstField, Double.parseDouble(entry.getKey()));
            break;
        case UUID:
            ps.setObject(firstField, UUID.fromString(entry.getKey()));
            break;
        case BOOLEAN:
            ps.setBoolean(firstField, Boolean.valueOf(entry.getKey()));
            break;
        }
        firstField++;
    }
    return ps;
}

From source file:com.ushahidi.swiftriver.core.api.dao.impl.JpaIdentityDao.java

/**
 * Insert new identities in a single batch statement
 * //  w  w  w  . j  a  v  a 2s.c om
 * @param newIdentityIndex
 * @param drops
 */
private void batchInsert(final Map<String, List<Integer>> newIdentityIndex, final List<Drop> drops,
        Sequence seq) {

    final List<String> hashes = new ArrayList<String>();
    hashes.addAll(newIdentityIndex.keySet());
    final long startKey = sequenceDao.getIds(seq, hashes.size());

    String sql = "INSERT INTO identities (id, hash, channel, " + "identity_orig_id, identity_username, "
            + "identity_name, identity_avatar) " + "VALUES (?,?,?,?,?,?,?)";

    jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
        public void setValues(PreparedStatement ps, int i) throws SQLException {
            String hash = hashes.get(i);

            // Update drops with the newly generated id
            for (int index : newIdentityIndex.get(hash)) {
                drops.get(index).getIdentity().setId(startKey + i);
            }

            Drop drop = drops.get(newIdentityIndex.get(hash).get(0));
            ps.setLong(1, drop.getIdentity().getId());
            ps.setString(2, drop.getIdentity().getHash());
            ps.setString(3, drop.getChannel());
            ps.setString(4, drop.getIdentity().getOriginId());
            ps.setString(5, drop.getIdentity().getUsername());
            ps.setString(6, drop.getIdentity().getName());
            ps.setString(7, drop.getIdentity().getAvatar());
        }

        public int getBatchSize() {
            return hashes.size();
        }
    });

}

From source file:com.amazonbird.announce.ProductMgrImpl.java

public List<Announcer> getAnnouncerWhoViewedProduct(long productId) {
    ArrayList<Announcer> announcerList = new ArrayList<Announcer>();
    String query = "select distinct announcer.id as id, announcer.consumerKey as consumerKey, "
            + "announcer.consumerSecret as consumerSecret, announcer.accessToken as accessToken, announcer.accessTokenSecret as accessTokenSecret, "
            + "announcer.name as name, announcer.surname as surname, announcer.password as password, "
            + "announcer.email as email, announcer.screenName as screenName, announcer.suspended as suspended, "
            + "announcer.creationtime as creationtime, announcer.training as training, announcer.maxFamousAccount2Follow as maxFamousAccount2Follow, "
            + "announcer.famousAccountFollowed as famousAccountFollowed, announcer.following as following, announcer.follower as follower, "
            + "announcer.authtoken as authtoken, announcer.sesid as sesid, announcer.suspensiontime as suspensiontime, announcer.description as description, "
            + "announcer.url as url, announcer.longName as longName, announcer.location as location, announcer.pictureUrl as pictureUrl "
            + " from announcer, announcement, product, click where click.announcementid = announcement.id and announcement.productid = product.id and announcement.customerid = announcer.id  and product.id = ?";
    Connection connection = null;
    PreparedStatement ps = null;
    ResultSet rs = null;// w ww  .j  ava2 s  . com

    try {
        connection = dbMgr.getConnection();
        ps = connection.prepareStatement(query);
        ps.setLong(1, productId);
        rs = ps.executeQuery();
        while (rs.next()) {
            Announcer announcer = new Announcer();
            announcer.getDataFromResultSet(rs);
            announcerList.add(announcer);
        }
        logger.debug(DBConstants.QUERY_EXECUTION_SUCC + ps.toString());
    } catch (SQLException ex) {
        logger.error(DBConstants.QUERY_EXECUTION_FAIL + ps.toString(), ex);

    } finally {
        dbMgr.closeResources(connection, ps, rs);
    }
    return announcerList;
}