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:com.l2jfree.gameserver.communitybbs.bb.Post.java

public void insertindb(CPost cp) {
    Connection con = null;//from   w w  w  . jav  a  2s.  c om
    try {
        con = L2DatabaseFactory.getInstance().getConnection(con);
        PreparedStatement statement = con.prepareStatement(
                "INSERT INTO posts (post_id,post_owner_name,post_ownerid,post_date,post_topic_id,post_forum_id,post_txt) values (?,?,?,?,?,?,?)");
        statement.setInt(1, cp.postId);
        statement.setString(2, cp.postOwner);
        statement.setInt(3, cp.postOwnerId);
        statement.setLong(4, cp.postDate);
        statement.setInt(5, cp.postTopicId);
        statement.setInt(6, cp.postForumId);
        statement.setString(7, cp.postTxt);
        statement.execute();
        statement.close();
    } catch (Exception e) {
        _log.warn("error while saving new Post to db ", e);
    } finally {
        L2DatabaseFactory.close(con);
    }
}

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

private long meanTimeBetweenFailures(String url, TimeRange timeRange) {
    Connection con = Utility.getPerformanceDBConnection();
    PreparedStatement com = null;
    ResultSet rs = null;//from   w w w.ja  va2s  .  co  m
    try {
        List<Long> faults = new ArrayList<Long>();

        com = con.prepareStatement(
                "select utcdatetime from rawdata where uri=? and success=false and (utcdatetime > ?) and (utcdatetime < ?);");
        com.setString(1, url);
        com.setLong(2, timeRange.getStart().getTimeInMillis());
        com.setLong(3, timeRange.getEnd().getTimeInMillis());
        rs = com.executeQuery();
        while (rs.next()) {
            faults.add(rs.getLong(1));

        }

        if (faults.isEmpty()) {
            return 0;
        }
        Collections.sort(faults);
        long diff = 0;
        for (int i = 1; i < faults.size(); i++) {
            diff += (faults.get(i) - faults.get(i - 1));
        }
        return diff / (faults.size() - 1);

    } catch (Exception ex) {
        log.log(Level.DEBUG, null, ex);
        //log.log(Level.WARN, "error calculating mtbf", ex);
        //not really important
        //expecting divid by 0 is there's no faults, etc
    } finally {
        DBUtils.safeClose(rs);
        DBUtils.safeClose(com);
        DBUtils.safeClose(con);
    }
    return -1;
}

From source file:net.bhira.sample.api.dao.EmployeeDaoImpl.java

/**
 * @see net.bhira.sample.api.dao.EmployeeDao#save(net.bhira.sample.model.Employee)
 *///from w ww  . j  a  va 2  s  . c  o m
@Override
public void save(Employee employee)
        throws ObjectNotFoundException, InvalidObjectException, InvalidReferenceException {
    try {
        if (employee == null) {
            throw new InvalidObjectException("Employee object is null.");
        }

        employee.initForSave();
        employee.validate();
        boolean isNew = employee.isNew();
        int count = 0;

        if (isNew) {
            // for new employee, construct SQL insert statement
            KeyHolder keyHolder = new GeneratedKeyHolder();
            count = jdbcTemplate.update(new PreparedStatementCreator() {
                public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                    PreparedStatement pstmt = connection.prepareStatement(SQL_INSERT,
                            Statement.RETURN_GENERATED_KEYS);
                    pstmt.setLong(1, employee.getCompanyId());
                    if (employee.getDepartmentId() == 0) {
                        pstmt.setNull(2, java.sql.Types.BIGINT);
                    } else {
                        pstmt.setLong(2, employee.getDepartmentId());
                    }
                    pstmt.setString(3, employee.getName());
                    if (employee.getManagerId() == 0) {
                        pstmt.setNull(4, java.sql.Types.BIGINT);
                    } else {
                        pstmt.setLong(4, employee.getManagerId());
                    }
                    pstmt.setString(5, employee.getSalutation());
                    pstmt.setString(6, employee.getSex() == null ? null : employee.getSex().toString());
                    pstmt.setDate(7, employee.getDOB() == null ? null : new Date(employee.getDOB().getTime()));
                    pstmt.setString(8, employee.getTitle());
                    pstmt.setString(9, employee.getAddress());
                    pstmt.setTimestamp(10, new Timestamp(employee.getCreated().getTime()));
                    pstmt.setTimestamp(11, new Timestamp(employee.getModified().getTime()));
                    pstmt.setString(12, employee.getCreatedBy());
                    pstmt.setString(13, employee.getModifiedBy());
                    return pstmt;
                }
            }, keyHolder);

            // fetch the newly created auto-increment ID
            employee.setId(keyHolder.getKey().longValue());
            LOG.debug("inserted employee, count = {}, id = {}", count, employee.getId());

        } else {
            // for existing employee, construct SQL update statement
            Long deptId = employee.getDepartmentId() == 0 ? null : employee.getDepartmentId();
            Long mgrId = employee.getManagerId() == 0 ? null : employee.getManagerId();
            String sex = employee.getSex() == null ? null : employee.getSex().toString();
            Date dob = employee.getDOB() == null ? null : new Date(employee.getDOB().getTime());
            Object[] args = new Object[] { employee.getCompanyId(), deptId, employee.getName(), mgrId,
                    employee.getSalutation(), sex, dob, employee.getTitle(), employee.getAddress(),
                    employee.getModified(), employee.getModifiedBy(), employee.getId() };
            count = jdbcTemplate.update(SQL_UPDATE, args);
            LOG.debug("updated employee, count = {}, id = {}", count, employee.getId());
        }

        // if insert/update has 0 count value, then rollback
        if (count <= 0) {
            throw new ObjectNotFoundException("Employee with ID " + employee.getId() + " was not found.");
        }

        // update dependent entries, as needed
        if (isNew) {

            // for new model if there is contact info, save it to contact info table and then
            // add entry in relationship table
            if (employee.getContactInfo() != null) {
                contactInfoDao.save(employee.getContactInfo());
                Object[] args = new Object[] { employee.getId(), employee.getContactInfo().getId() };
                jdbcTemplate.update(SQL_CINFO_REL_INSERT, args);
            }

        } else {
            // for existing model, fetch contact info ID from relationship table
            List<Long> cinfoIds = jdbcTemplate.queryForList(SQL_CINFO_REL_LOAD, Long.class,
                    new Object[] { employee.getId() });
            Long cinfoId = (cinfoIds != null && !cinfoIds.isEmpty()) ? cinfoIds.get(0) : null;

            if (employee.getContactInfo() == null) {
                // clean up old contact info entry, if needed
                if (cinfoId != null) {
                    jdbcTemplate.update(SQL_CINFO_REL_DELETE, new Object[] { employee.getId() });
                    contactInfoDao.delete(cinfoId);
                }

            } else {
                // insert/update contact info entry
                if (cinfoId != null) {
                    employee.getContactInfo().setId(cinfoId);
                    contactInfoDao.save(employee.getContactInfo());
                } else {
                    contactInfoDao.save(employee.getContactInfo());
                    Object[] args = new Object[] { employee.getId(), employee.getContactInfo().getId() };
                    jdbcTemplate.update(SQL_CINFO_REL_INSERT, args);
                }
            }
        }

    } catch (DataIntegrityViolationException dive) {
        String msg = dive.getMessage();
        if (msg != null) {
            if (msg.contains("fk_employee_compy")) {
                throw new InvalidReferenceException("Invalid reference for attribute 'companyId'", dive);
            } else if (msg.contains("fk_employee_dept")) {
                throw new InvalidReferenceException("Invalid reference for attribute 'departmentId'", dive);
            } else if (msg.contains("fk_employee_mgr")) {
                throw new InvalidReferenceException("Invalid reference for attribute 'managerId'", dive);
            }
        }
        throw dive;
    }
}

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

/**
 * Populate the droplet media table.//from  w  w w. j  ava 2 s.  c o m
 * 
 * @param drops
 */
private void insertDropletMedia(List<Drop> drops) {

    // List of drop IDs in the drops list
    List<Long> dropIds = new ArrayList<Long>();
    // List of media in a drop
    Map<Long, Set<Long>> dropletMediaMap = new HashMap<Long, Set<Long>>();
    // List of drops and the media that is the drop image
    final List<long[]> dropImages = new ArrayList<long[]>();
    for (Drop drop : drops) {

        if (drop.getMedia() == null)
            continue;

        dropIds.add(drop.getId());

        for (Media media : drop.getMedia()) {
            Set<Long> m = null;
            if (dropletMediaMap.containsKey(drop.getId())) {
                m = dropletMediaMap.get(drop.getId());
            } else {
                m = new HashSet<Long>();
                dropletMediaMap.put(drop.getId(), m);
            }

            // Is this the drop image?
            if (drop.getImage() != null && media.getUrl().equals(drop.getImage().getUrl())) {
                long[] dropImage = { drop.getId(), media.getId() };
                dropImages.add(dropImage);
            }

            m.add(media.getId());
        }
    }

    // Find droplet media that already exist in the db
    String sql = "SELECT droplet_id, media_id FROM droplets_media WHERE droplet_id in (:ids)";

    MapSqlParameterSource params = new MapSqlParameterSource();
    params.addValue("ids", dropIds);

    List<Map<String, Object>> results = this.namedJdbcTemplate.queryForList(sql, params);

    // Remove already existing droplet_media from our Set
    for (Map<String, Object> result : results) {
        long dropletId = ((Number) result.get("droplet_id")).longValue();
        long mediaId = ((Number) result.get("media_id")).longValue();

        Set<Long> mediaSet = dropletMediaMap.get(dropletId);
        if (mediaSet != null) {
            mediaSet.remove(mediaId);
        }
    }

    // Insert the remaining items in the set into the db
    sql = "INSERT INTO droplets_media (droplet_id, media_id) VALUES (?,?)";

    final List<long[]> dropletMediaList = new ArrayList<long[]>();
    for (Long dropletId : dropletMediaMap.keySet()) {
        for (Long mediaId : dropletMediaMap.get(dropletId)) {
            long[] dropletMedia = { dropletId, mediaId };
            dropletMediaList.add(dropletMedia);
        }
    }
    jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
        public void setValues(PreparedStatement ps, int i) throws SQLException {
            long[] dropletMedia = dropletMediaList.get(i);
            ps.setLong(1, dropletMedia[0]);
            ps.setLong(2, dropletMedia[1]);
        }

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

    if (dropImages.size() > 0) {
        sql = "UPDATE droplets SET droplet_image = ? WHERE id = ?";
        jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                long[] update = dropImages.get(i);
                ps.setLong(1, update[1]);
                ps.setLong(2, update[0]);
            }

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

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

@Override
public Files getFileById(Long id) {
    Connection con = null;/*from w w w  .  j  a va 2 s  .  c  o m*/
    PreparedStatement statement = null;
    String sql = "select * from " + Files.FilesFieldsKey.TABLE + " where id=?";
    Files fStat = new Files();
    try {
        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;
}

From source file:com.its.core.local.hezhou.task.ExportImageFilesReadTask.java

private void updateRecordStatus(Connection conn, long id) throws Exception {
    PreparedStatement preStatement = null;
    try {/* w  w w . ja v  a  2 s  .c  om*/
        log.debug(this.getUpdateImageFileRecordSql());
        preStatement = conn.prepareStatement(this.getUpdateImageFileRecordSql());
        preStatement.setLong(1, id);
        preStatement.executeUpdate();
    } catch (Exception ex) {
        log.error(ex.getMessage(), ex);
        throw ex;
    } finally {
        DatabaseHelper.close(null, preStatement);
    }
}

From source file:net.mindengine.oculus.frontend.service.customization.JdbcCustomizationDAO.java

@Override
public Long addCustomization(Customization customization) throws Exception {
    PreparedStatement ps = getConnection()
            .prepareStatement("insert into customizations " + "(unit, " + "project_id, " + "name, "
                    + "description, " + "type, " + "subtype, " + "group_name) values (?,?,?,?,?,?,?)");

    ps.setString(1, customization.getUnit());
    ps.setLong(2, customization.getProjectId());
    ps.setString(3, customization.getName());
    ps.setString(4, customization.getDescription());
    ps.setString(5, customization.getType());
    ps.setString(6, customization.getSubtype());
    ps.setString(7, customization.getGroupName());
    logger.info(ps);//from w w w .java  2s  . co  m
    ps.execute();

    ResultSet rs = ps.getGeneratedKeys();
    if (rs.next()) {
        return rs.getLong(1);
    }
    return null;
}

From source file:nl.ordina.bag.etl.dao.postgres.BAGMutatiesDAOImpl.java

@Override
public void insert(final BAGMutatie mutatie) throws DAOException {
    try {/*from ww  w.  jav a  2s  .c om*/
        jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                try {
                    PreparedStatement ps = connection.prepareStatement("insert into bag_mutatie (" + "id,"
                            + "tijdstip_verwerking," + "volgnr_verwerking," + "object_type," + "mutatie_product"
                            + ") values ((select coalesce(max(id),0) + 1 from bag_mutatie),?,?,?,?)");
                    ps.setTimestamp(1, Utils.toTimestamp(mutatie.getTijdstipVerwerking()));
                    ps.setLong(2, mutatie.getVolgnrVerwerking());
                    ps.setInt(3, mutatie.getObjectType().ordinal());
                    ps.setString(4, XMLMessageBuilder.getInstance(MutatieProduct.class)
                            .handle(new JAXBElement<MutatieProduct>(new QName(
                                    "http://www.kadaster.nl/schemas/bag-verstrekkingen/extract-producten-lvc/v20090901",
                                    "Mutatie-product"), MutatieProduct.class, mutatie.getMutatieProduct())));
                    return ps;
                } catch (JAXBException e) {
                    throw new DAOException(e);
                }
            }
        });
    } catch (DataAccessException e) {
        throw new DAOException(e);
    }
}

From source file:com.flexive.ejb.beans.HistoryTrackerEngineBean.java

/**
 * {@inheritDoc}//from   w ww  .ja v a  2  s . c  o  m
 */
@Override
public List<FxHistory> getContentEntries(long contentId) {
    List<FxHistory> ret = new ArrayList<FxHistory>(100);
    Connection con = null;
    PreparedStatement ps = null;
    try {
        con = Database.getDbConnection();
        ps = con.prepareStatement(
                StorageManager.escapeReservedWords(HISTORY_SELECT) + " WHERE PKID=? ORDER BY TIMESTP");
        ps.setLong(1, contentId);
        ResultSet rs = ps.executeQuery();
        boolean loadData = FxContext.getUserTicket().isGlobalSupervisor();
        while (rs != null && rs.next())
            ret.add(new FxHistory(rs.getLong(3), rs.getLong(1), rs.getString(2), rs.getString(4),
                    rs.getString(5).split("\\|"), rs.getLong(8), rs.getLong(9), rs.getInt(10), rs.getString(6),
                    rs.getString(7), loadData ? rs.getString(11) : "No permission to load to data!",
                    rs.getString(12)));
    } catch (Exception ex) {
        LOG.error(ex.getMessage());
    } finally {
        Database.closeObjects(HistoryTrackerEngineBean.class, con, ps);
    }
    return ret;
}

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

@Override
public FileStatistic getFileStatisticById(Long id) {
    Connection con = null;//from w  w w. j  a  va 2s  .c om
    PreparedStatement statement = null;
    String sql = "select * from " + FileStatistic.FileStatisticKey.TABLE + " where id=?";
    FileStatistic fStat = new FileStatistic();
    try {
        con = DBConnector.getConnection();
        con.setAutoCommit(false);
        statement = con.prepareStatement(sql);
        statement.setLong(1, id);
        ResultSet rs = statement.executeQuery();
        ResultSetToFileStatistic(rs, fStat);
        con.commit();
    } catch (SQLException e) {
        handleException(e, con);
    } finally {
        doFinal(con, statement);
    }
    return fStat;
}