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:org.bremersee.common.security.acls.jdbc.BasicLookupStrategy.java

/**
 * Locates the primary key IDs specified in "findNow", adding AclImpl instances with
 * StubAclParents to the "acls" Map.//from  w w w .  j a  v  a2 s  . c  o  m
 *
 * @param acls the AclImpls (with StubAclParents)
 * @param findNow Long-based primary keys to retrieve
 * @param sids the sids
 */
private void lookupPrimaryKeys(final Map<Serializable, Acl> acls, final Set<Long> findNow,
        final List<Sid> sids) {
    Assert.notNull(acls, "ACLs are required");
    Assert.notEmpty(findNow, "Items to find now required");

    String sql = computeRepeatingSql(lookupPrimaryKeysWhereClause, findNow.size());

    Set<Long> parentsToLookup = jdbcTemplate.query(sql, new PreparedStatementSetter() {
        @Override
        public void setValues(PreparedStatement ps) throws SQLException {
            int i = 0;

            for (Long toFind : findNow) {
                i++;
                ps.setLong(i, toFind);
            }
        }
    }, new ProcessResultSet(acls, sids));

    // Lookup the parents, now that our JdbcTemplate has released the database
    // connection (SEC-547)
    if (!parentsToLookup.isEmpty()) {
        lookupPrimaryKeys(acls, parentsToLookup, sids);
    }
}

From source file:com.tascape.qa.th.db.H2Handler.java

@Override
protected void queueTestCaseResults(String execId, List<TestCase> tests) throws SQLException {
    LOG.info("Queue {} test case result(s) with execution id {} ", tests.size(), execId);
    final String sql = "INSERT INTO " + TestResult.TABLE_NAME + " (" + Test_Result.TEST_RESULT_ID.name() + ", "
            + Test_Result.SUITE_RESULT.name() + ", " + Test_Result.TEST_CASE_ID.name() + ", "
            + Test_Result.EXECUTION_RESULT.name() + ", " + Test_Result.START_TIME.name() + ", "
            + Test_Result.STOP_TIME.name() + ", " + Test_Result.TEST_STATION.name() + ", "
            + Test_Result.LOG_DIR.name() + ") VALUES (?,?,?,?,?,?,?,?);";
    Map<String, Integer> idMap = this.getTestCaseIds(tests);

    try (Connection conn = this.getConnection()) {
        PreparedStatement stmt = conn.prepareStatement(sql);

        int index = 0;
        for (TestCase test : tests) {
            Integer tcid = idMap.get(test.format());
            if (tcid == null) {
                tcid = this.getTestCaseId(test);
            }/*w  ww . ja  va 2  s  . c  om*/

            Long time = System.currentTimeMillis();
            stmt.setString(1, Utils.getUniqueId());
            stmt.setString(2, execId);
            stmt.setInt(3, tcid);
            stmt.setString(4, ExecutionResult.QUEUED.name());
            stmt.setLong(5, time);
            stmt.setLong(6, time + 11);
            stmt.setString(7, "?");
            stmt.setString(8, "?");
            LOG.debug("{}", stmt);
            int i = stmt.executeUpdate();
        }
    }
}

From source file:com.salesmanager.core.service.catalog.impl.db.dao.CategoryDao.java

public void save(final Category instance) {
    getHibernateTemplate().execute(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Connection con = session.connection();
            PreparedStatement ps = con
                    .prepareStatement("insert into categories(categories_id,categories_image,parent_id,"
                            + "sort_order,date_added,last_modified,categories_status,visible,RefCategoryID,"
                            + "RefCategoryLevel,RefCategoryName,RefCategoryParentID,RefExpired,merchantid,depth,"
                            + "lineage) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
            ps.setLong(1, instance.getCategoryId());
            ps.setString(2, instance.getCategoryImage());
            ps.setLong(3, instance.getParentId());
            ps.setInt(4, (instance.getSortOrder() == null ? 0 : instance.getSortOrder()));
            ps.setDate(5, new java.sql.Date(instance.getDateAdded().getTime()));
            ps.setDate(6, new java.sql.Date(instance.getLastModified().getTime()));
            ps.setBoolean(7, instance.isCategoryStatus());
            ps.setBoolean(8, instance.isVisible());
            ps.setLong(9, instance.getRefCategoryId());
            ps.setInt(10, instance.getRefCategoryLevel());
            ps.setString(11, instance.getRefCategoryName());
            ps.setString(12, instance.getRefCategoryParentId());
            ps.setString(13, instance.getRefExpired());
            ps.setLong(14, instance.getMerchantId());
            ps.setInt(15, instance.getDepth());
            ps.setString(16, instance.getLineage());
            return ps.executeUpdate();
        }/*w  w w. j a v a  2  s. co m*/

    });
}

From source file:com.softberries.klerk.dao.AddressDao.java

public void create(Address c, QueryRunner run, Connection conn, ResultSet generatedKeys) throws SQLException {
    PreparedStatement st = conn.prepareStatement(SQL_INSERT_ADDRESS, Statement.RETURN_GENERATED_KEYS);
    st.setString(1, c.getCountry());// ww w  . java  2  s .c o m
    st.setString(2, c.getCity());
    st.setString(3, c.getStreet());
    st.setString(4, c.getPostCode());
    st.setString(5, c.getHouseNumber());
    st.setString(6, c.getFlatNumber());
    st.setString(7, c.getNotes());
    st.setBoolean(8, c.isMain());
    if (c.getPerson_id().longValue() == 0 && c.getCompany_id().longValue() == 0) {
        throw new SQLException("For Address either Person or Company needs to be specified");
    }
    if (c.getPerson_id().longValue() != 0) {
        st.setLong(9, c.getPerson_id());
    } else {
        st.setNull(9, java.sql.Types.NUMERIC);
    }
    if (c.getCompany_id().longValue() != 0) {
        st.setLong(10, c.getCompany_id());
    } else {
        st.setNull(10, java.sql.Types.NUMERIC);
    }
    // run the query
    int i = st.executeUpdate();
    System.out.println("i: " + i);
    if (i == -1) {
        System.out.println("db error : " + SQL_INSERT_ADDRESS);
    }
    generatedKeys = st.getGeneratedKeys();
    if (generatedKeys.next()) {
        c.setId(generatedKeys.getLong(1));
    } else {
        throw new SQLException("Creating address failed, no generated key obtained.");
    }
}

From source file:com.pactera.edg.am.metamanager.extractor.dao.helper.CreateDependencyHelper.java

private void myDoInPreparedStatement(long sysTime, MMDDependency dependency, PreparedStatement ps)
        throws SQLException {

    String ownerModelId = dependency.getOwnerMetadata().getClassifierId();
    String valueModelId = dependency.getValueMetadata().getClassifierId();

    try {//  www .  j a v a  2 s . co  m
        // ?ID
        ps.setString(1, dependency.getOwnerMetadata().getId());
        // ?ID
        ps.setString(2, ownerModelId);
        // ?ID
        ps.setString(3, dependency.getValueMetadata().getId());
        // ?ID
        ps.setString(4, valueModelId);
        // ???
        ps.setString(5, dependency.getCode());
        // 
        ps.setLong(6, sysTime);
        ps.setString(7, "1");
        ps.setString(8, "1");

        setPs(ps, 8);

        ps.addBatch();
        // ??
        ps.clearParameters();
        if (++super.count % super.batchSize == 0) {
            ps.executeBatch();
            ps.clearBatch();
        }
    } catch (SQLException e) {
        String logMsg = new StringBuilder().append("?,?:??ID:")
                .append(dependency.getOwnerMetadata().getId()).append(",?:")
                .append(ownerModelId).append(",??ID:")
                .append(dependency.getValueMetadata().getId()).append(",?:")
                .append(valueModelId).append(", ???:").append(dependency.getCode()).toString();
        log.error(logMsg);
        AdapterExtractorContext.addExtractorLog(ExtractorLogLevel.ERROR, logMsg);
        throw e;
    }
}

From source file:architecture.ee.web.community.page.dao.jdbc.JdbcPageDao.java

private void insertProperties(Page page) {
    if (page.getProperties() != null && !page.getProperties().isEmpty()) {
        Map<String, String> properties = page.getProperties();
        final List<Map.Entry<String, String>> entryList = new ArrayList<Map.Entry<String, String>>(
                properties.entrySet());// w w  w .j a va 2s .c om
        final long pageId = page.getPageId();
        final long pageVersionId = page.getVersionId();
        getExtendedJdbcTemplate().batchUpdate(
                getBoundSql("ARCHITECTURE_COMMUNITY.INSERT_PAGE_PROPERTY").getSql(),
                new BatchPreparedStatementSetter() {
                    public int getBatchSize() {
                        return entryList.size();
                    }

                    public void setValues(PreparedStatement ps, int index) throws SQLException {
                        Map.Entry<String, String> e = entryList.get(index);
                        ps.setLong(1, pageId);
                        ps.setLong(2, pageVersionId);
                        ps.setString(3, e.getKey());
                        ps.setString(4, e.getValue());
                    }
                });
    }
}

From source file:de.ingrid.importer.udk.strategy.v1.IDCStrategy1_0_4_fixInspireThemes.java

/** Create "searchterm_value" of INSPIRE theme if not present and assign to object via "searchterm_obj". */
private void addInspireThemeToObject(int themeIdToAdd, long objectId, int line,
        HashMap<Integer, Long> themeIdToSearchtermId, PreparedStatement psInsertTerm,
        PreparedStatement psInsertTermObj, Set<Integer> currThemeIds, String searchtermForLog,
        String objUuidForLog, String workStateForLog) throws Exception {

    String themeName = UtilsInspireThemes.inspireThemes_de.get(themeIdToAdd);

    // first add inspire term to searchterms if not present yet !
    Long searchtermId = themeIdToSearchtermId.get(themeIdToAdd);
    if (searchtermId == null) {
        int cnt = 1;

        searchtermId = getNextId();//from ww  w  .  j a v  a 2  s .  c o m
        psInsertTerm.setLong(cnt++, searchtermId); // searchterm_value.id
        psInsertTerm.setString(cnt++, themeName); // searchterm_value.term
        psInsertTerm.setInt(cnt++, themeIdToAdd); // searchterm_value.entry_id
        psInsertTerm.executeUpdate();

        themeIdToSearchtermId.put(themeIdToAdd, searchtermId);
    }

    // assign searchterm to object
    int cnt = 1;
    psInsertTermObj.setLong(cnt++, getNextId()); // searchterm_obj.id
    psInsertTermObj.setLong(cnt++, objectId); // searchterm_obj.obj_id
    psInsertTermObj.setInt(cnt++, line); // searchterm_obj.line
    psInsertTermObj.setLong(cnt++, searchtermId); // searchterm_obj.searchterm_id
    psInsertTermObj.executeUpdate();

    // also update our set !
    currThemeIds.add(themeIdToAdd);
    numObjThemesAdded++;

    if (log.isDebugEnabled()) {
        String msg = "Added INSPIRE Theme: '" + themeName + "'";
        if (searchtermForLog != null) {
            msg = msg + ", Searchterm: '" + searchtermForLog + "'";
        }
        msg = msg + ", Obj-UUUID: " + objUuidForLog + ", workState: '" + workStateForLog + "'";

        log.debug(msg);
    }
}

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

/**
 * Insert new media in a single batch statement
 * //w  w  w .j  av  a  2s.c o m
 * @param newMediaIndex
 * @param drops
 */
private void batchInsert(final Map<String, List<int[]>> newMediaIndex, final List<Drop> drops, Sequence seq) {

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

    String sql = "INSERT INTO media (id, hash, url, type) " + "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 : newMediaIndex.get(hash)) {
                drops.get(index[0]).getMedia().get(index[1]).setId(startKey + i);
            }

            int[] index = newMediaIndex.get(hash).get(0);
            Media media = drops.get(index[0]).getMedia().get(index[1]);
            ps.setLong(1, media.getId());
            ps.setString(2, media.getHash());
            ps.setString(3, media.getUrl());
            ps.setString(4, media.getType());
        }

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

    // Media Thumbnails
    sql = "INSERT INTO media_thumbnails(`media_id`, `size`, `url`) VALUES(?, ?, ?)";
    jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {

        private int thumbnailCount = 0;

        public void setValues(PreparedStatement ps, int i) throws SQLException {
            String hash = hashes.get(i);
            int[] index = newMediaIndex.get(hash).get(0);
            Media media = drops.get(index[0]).getMedia().get(index[1]);

            for (MediaThumbnail thumbnail : media.getThumbnails()) {
                ps.setLong(1, media.getId());
                ps.setInt(2, thumbnail.getSize());
                ps.setString(3, thumbnail.getUrl());

                thumbnailCount++;
            }
        }

        public int getBatchSize() {
            return thumbnailCount;
        }
    });

    // Update the droplet_media table
    insertDropletMedia(drops);

}

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

/**
 * {@inheritDoc}//from  w w w . j  ava  2 s . c o m
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void removeMetaData(int mandatorId) throws FxApplicationException {
    final UserTicket ticket = FxContext.getUserTicket();
    final FxEnvironment environment;
    final long metadataId = -1;
    // Security
    FxPermissionUtils.checkRole(ticket, Role.GlobalSupervisor);
    environment = CacheAdmin.getEnvironment();
    // check existance
    Mandator mand = environment.getMandator(mandatorId);
    Connection con = null;
    PreparedStatement ps = null;
    String sql;

    try {
        // get Database connection
        con = Database.getDbConnection(); //1            //2        //3
        sql = "UPDATE " + TBL_MANDATORS + " SET METADATA=NULL, MODIFIED_BY=?, MODIFIED_AT=? WHERE ID=?";
        final long NOW = System.currentTimeMillis();
        ps = con.prepareStatement(sql);
        ps.setLong(1, ticket.getUserId());
        ps.setLong(2, NOW);
        ps.setLong(3, mandatorId);
        ps.executeUpdate();
        StructureLoader.updateMandator(FxContext.get().getDivisionId(),
                new Mandator(mand.getId(), mand.getName(), metadataId, true,
                        new LifeCycleInfoImpl(mand.getLifeCycleInfo().getCreatorId(),
                                mand.getLifeCycleInfo().getCreationTime(), ticket.getUserId(), NOW)));
    } catch (SQLException e) {
        EJBUtils.rollback(ctx);
        throw new FxUpdateException(LOG, e, "ex.mandator.removeMetaDataFailed", mand.getMetadataId(),
                mand.getName(), mand.getId(), e.getMessage());
    } finally {
        Database.closeObjects(MandatorEngineBean.class, con, ps);
    }
}

From source file:net.mindengine.oculus.frontend.service.issue.JdbcIssueDAO.java

@Override
public long createIssue(Issue issue) throws Exception {
    PreparedStatement ps = getConnection().prepareStatement(
            "insert into issues (name, link, summary, description, author_id, date, fixed, fixed_date, project_id, subproject_id) "
                    + "values (?,?,?,?,?,?,?,?,?,?)");

    ps.setString(1, issue.getName());/*from   w w w . ja v  a  2 s .c o m*/
    ps.setString(2, issue.getLink());
    ps.setString(3, issue.getSummary());
    ps.setString(4, issue.getDescription());
    ps.setLong(5, issue.getAuthorId());
    ps.setTimestamp(6, new Timestamp(issue.getDate().getTime()));
    ps.setInt(7, issue.getFixed());
    ps.setTimestamp(8, new Timestamp(issue.getFixedDate().getTime()));
    ps.setLong(9, issue.getProjectId());
    ps.setLong(10, issue.getSubProjectId());

    logger.info(ps);

    ps.execute();

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