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:gobblin.data.management.retention.sql.SqlBasedRetentionPoc.java

private void insertSnapshot(Path snapshotPath) throws Exception {

    String datasetPath = StringUtils.substringBeforeLast(snapshotPath.toString(), Path.SEPARATOR);
    String snapshotName = StringUtils.substringAfterLast(snapshotPath.toString(), Path.SEPARATOR);
    long ts = Long.parseLong(StringUtils.substringBefore(snapshotName, "-PT-"));
    long recordCount = Long.parseLong(StringUtils.substringAfter(snapshotName, "-PT-"));

    PreparedStatement insert = connection.prepareStatement("INSERT INTO Snapshots VALUES (?, ?, ?, ?, ?)");
    insert.setString(1, datasetPath);/*  w w  w  . jav a2 s .co  m*/
    insert.setString(2, snapshotName);
    insert.setString(3, snapshotPath.toString());
    insert.setTimestamp(4, new Timestamp(ts));
    insert.setLong(5, recordCount);

    insert.executeUpdate();

}

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

private void updateRecordStatus(Connection conn, long id) throws Exception {
    PreparedStatement preStatement = null;
    try {/*  www .j a v a2 s.  com*/
        //         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:org.pegadi.server.score.ScoreServerImpl.java

/**
 * Starts score recording for a new game. The <code>Score</code> object that is
 * returned <i>must</i> be used when calling {@link #updateScore } and
 * {@link #endGame }, as each score has an unique ID.
 *
 * @param domain The domain for the game.
 * @return A new Score object, with the score set to 0. If the domain is not known,
 *         this method will return <code>null</code>.
 *///from w  ww.j  av  a 2  s.  c o  m

public Score startGame(final Person person, String domain) {

    if (domain.equals("tetris")) {
        final String insertSql = "insert into score_tetris (userID, score, level, linecount, starttime, active) values (?, ?, ?, ?, ?, true)";
        KeyHolder keyHolder = new GeneratedKeyHolder(); // The key/id of the new score is needed
        template.update(new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                PreparedStatement statement = con.prepareStatement(insertSql, new String[] { "ID" });
                statement.setString(1, person.getUsername());
                statement.setLong(2, 0); // score
                statement.setInt(3, 1); // level
                statement.setInt(4, 0); // lines
                statement.setTimestamp(5, new Timestamp((new GregorianCalendar()).getTimeInMillis()));

                return statement;
            }
        }, keyHolder);

        int scoreId = keyHolder.getKey().intValue();

        return new TetrisScore(scoreId, person.getUsername(), person.getName(), 1);
    } else {
        log.error("Domain '{}' not implemented yet!", domain);
        return null;
    }

}

From source file:com.mobilewallet.users.dao.UserDAO.java

public String getGCMID(long userId) {
    Connection connection = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;/*from w  w w .  j  av a  2  s.  co  m*/
    String gcmId = null;
    try {
        connection = dataSource.getConnection();
        pstmt = connection.prepareStatement(getGCMIDQuery);
        pstmt.setLong(1, userId);
        rs = pstmt.executeQuery();

        if (rs.next()) {
            gcmId = rs.getString("u_gcm_id");
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {

        try {
            if (rs != null) {
                rs.close();
            }
        } catch (Exception ex) {

        }
        try {
            if (pstmt != null) {
                pstmt.close();
            }
        } catch (Exception ex) {

        }
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (Exception ex) {

        }
    }
    return gcmId;
}

From source file:com.mobilewallet.users.dao.UserDAO.java

public User userInfo(long userId) {
    Connection connection = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;//from   ww w .  ja v  a2 s . c  om
    User user = null;
    try {
        connection = dataSource.getConnection();
        pstmt = connection.prepareStatement(getUserInfoQuery);
        pstmt.setLong(1, userId);
        rs = pstmt.executeQuery();

        if (rs.next()) {
            user = new User();
            user.setUserId(rs.getLong("u_id"));
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {

        try {
            if (rs != null) {
                rs.close();
            }
        } catch (Exception ex) {

        }
        try {
            if (pstmt != null) {
                pstmt.close();
            }
        } catch (Exception ex) {

        }
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (Exception ex) {

        }
    }
    return user;
}

From source file:com.flexive.core.storage.MySQL.MySQLSequencerStorage.java

/**
 * {@inheritDoc}//  w  ww .  ja va2  s . c om
 */
@Override
public void createSequencer(String name, boolean allowRollover, long startNumber)
        throws FxApplicationException {
    if (StringUtils.isEmpty(name) || name.toUpperCase().trim().startsWith("SYS_"))
        throw new FxCreateException(LOG, "ex.sequencer.create.invalid.name", name);
    name = name.toUpperCase().trim();
    if (sequencerExists(name))
        throw new FxCreateException(LOG, "ex.sequencer.create.invalid.name", name);

    Connection con = null;
    PreparedStatement ps = null;
    try {
        con = Database.getDbConnection();

        ps = con.prepareStatement(SQL_CREATE);
        ps.setLong(1, startNumber);
        ps.setString(2, name);
        ps.setBoolean(3, allowRollover);
        ps.executeUpdate();
        if (ps.getUpdateCount() == 0)
            throw new FxCreateException(LOG, "ex.sequencer.create.failed", name);
    } catch (SQLException exc) {
        throw new FxCreateException(LOG, exc, "ex.sequencer.create.failed", name);
    } finally {
        Database.closeObjects(MySQLSequencerStorage.class, con, ps);
    }
}

From source file:com.ccoe.build.dal.ProjectJDBCTemplate.java

public int create(final Project project, final String appName) {
    final String SQL = "insert into RBT_PROJECT (pool_name, name, group_id, artifact_id, type, version, "
            + "duration, status, start_time) " + "values (?, ?, ?, ?, ?, ?, ?, ?, ?)";

    KeyHolder keyHolder = new GeneratedKeyHolder();
    jdbcTemplateObject.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(SQL, new String[] { "id" });
            ps.setString(1, appName);/*from w w  w. jav  a  2  s  . c  om*/
            ps.setString(2, project.getName());
            ps.setString(3, project.getGroupId());
            ps.setString(4, project.getArtifactId());
            ps.setString(5, project.getType());
            ps.setString(6, project.getVersion());
            ps.setLong(7, project.getDuration());
            ps.setString(8, project.getStatus());
            ps.setTimestamp(9, new java.sql.Timestamp(project.getStartTime().getTime()));

            return ps;
        }
    }, keyHolder);

    return keyHolder.getKey().intValue();
}

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

/**
 * Populate the droplet tags table.//from   w w  w  .j  a va 2s.  co  m
 * 
 * @param drops
 */
private void insertDropletTags(List<Drop> drops) {

    // List of drop IDs in the drops list
    List<Long> dropIds = new ArrayList<Long>();
    // List of tags in a drop
    Map<Long, Set<Long>> dropletTagsMap = new HashMap<Long, Set<Long>>();
    for (Drop drop : drops) {

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

        dropIds.add(drop.getId());

        for (Tag tag : drop.getTags()) {
            Set<Long> tags = null;
            if (dropletTagsMap.containsKey(drop.getId())) {
                tags = dropletTagsMap.get(drop.getId());
            } else {
                tags = new HashSet<Long>();
                dropletTagsMap.put(drop.getId(), tags);
            }

            tags.add(tag.getId());
        }
    }

    // Find droplet tags that already exist in the db
    String sql = "SELECT droplet_id, tag_id FROM droplets_tags 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_tags from our Set
    for (Map<String, Object> result : results) {
        long dropletId = ((Number) result.get("droplet_id")).longValue();
        long tagId = ((Number) result.get("tag_id")).longValue();

        Set<Long> tagSet = dropletTagsMap.get(dropletId);
        if (tagSet != null) {
            tagSet.remove(tagId);
        }
    }

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

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

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

From source file:com.l2jfree.gameserver.idfactory.IdFactory.java

private void cleanUpTimeStamps() {
    Connection con = null;/*from  w w  w  .  ja v  a 2  s. co  m*/
    try {
        int cleanCount = 0;
        con = L2DatabaseFactory.getInstance().getConnection();
        PreparedStatement stmt;
        for (String line : TIMESTAMPS_CLEAN) {
            stmt = con.prepareStatement(line);
            stmt.setLong(1, System.currentTimeMillis());
            cleanCount += stmt.executeUpdate();
            stmt.close();
        }

        _log.info("Cleaned " + cleanCount + " expired timestamps from database.");
    } catch (SQLException e) {
    } finally {
        L2DatabaseFactory.close(con);
    }
}

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

/**
 * @see net.bhira.sample.api.dao.DepartmentDao#save(net.bhira.sample.model.Department)
 */// www  .ja v a  2  s .  com
@Override
public void save(Department department) throws ObjectNotFoundException, DuplicateNameException,
        InvalidObjectException, InvalidReferenceException {
    try {
        if (department == null) {
            throw new InvalidObjectException("Department object is null.");
        }

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

        if (isNew) {
            // for new department, 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, department.getCompanyId());
                    pstmt.setString(2, department.getName());
                    pstmt.setString(3, department.getBillingAddress());
                    pstmt.setString(4, department.getShippingAddress());
                    pstmt.setTimestamp(5, new Timestamp(department.getCreated().getTime()));
                    pstmt.setTimestamp(6, new Timestamp(department.getModified().getTime()));
                    pstmt.setString(7, department.getCreatedBy());
                    pstmt.setString(8, department.getModifiedBy());
                    return pstmt;
                }
            }, keyHolder);

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

        } else {
            // for existing department, construct SQL update statement
            Object[] args = new Object[] { department.getCompanyId(), department.getName(),
                    department.getBillingAddress(), department.getShippingAddress(), department.getModified(),
                    department.getModifiedBy(), department.getId() };
            count = jdbcTemplate.update(SQL_UPDATE, args);
            LOG.debug("updated department, count = {}, id = {}", count, department.getId());
        }

        // if insert/update has 0 count value, then rollback
        if (count <= 0) {
            throw new ObjectNotFoundException("Department with ID " + department.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 (department.getContactInfo() != null) {
                contactInfoDao.save(department.getContactInfo());
                Object[] args = new Object[] { department.getId(), department.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[] { department.getId() });
            Long cinfoId = (cinfoIds != null && !cinfoIds.isEmpty()) ? cinfoIds.get(0) : null;

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

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

    } catch (DataIntegrityViolationException dive) {
        String msg = dive.getMessage();
        if (msg != null) {
            if (msg.contains("uq_department")) {
                throw new DuplicateNameException("Duplicate department name " + department.getName(), dive);
            } else if (msg.contains("fk_department_compy")) {
                throw new InvalidReferenceException("Invalid reference for attribute 'companyId'", dive);
            }
        }
        throw dive;
    }
}