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.amazonbird.announce.ProductMgrImpl.java

public Product addProduct(Product product) {
    Connection connection = null;
    PreparedStatement ps = null;

    ResultSet rs = null;//  ww  w  .j  a va2s.  c o m

    try {
        connection = dbMgr.getConnection();
        ps = connection.prepareStatement(ADD_PRODUCT, Statement.RETURN_GENERATED_KEYS);
        ps.setString(1, product.getName());
        ps.setDouble(2, product.getPrice());
        ps.setString(3, product.getDestination());
        ps.setString(4, product.getAlternativeDestionation());
        ps.setString(5, product.getLocale());
        ps.setLong(6, product.getAnnouncerId());

        ps.executeUpdate();

        rs = ps.getGeneratedKeys();
        if (rs.next()) {
            long productId = rs.getLong(1);
            product.setId(productId);
        }

        logger.debug(DBConstants.QUERY_EXECUTION_SUCC + ps.toString());
    } catch (MySQLIntegrityConstraintViolationException e) {

        logger.error("Error: " + e.getMessage() + "\nProduct:" + product.toString());
    } catch (SQLException ex) {
        logger.error(DBConstants.QUERY_EXECUTION_FAIL + ps.toString(), ex);
    } finally {
        dbMgr.closeResources(connection, ps, rs);
    }
    return product;
}

From source file:com.flexive.ejb.beans.structure.SelectListEngineBean.java

/**
 * {@inheritDoc}/*from   w  w w.jav a  2s .  co m*/
 */
@Override
public long getSelectListItemInstanceCount(long selectListItemId) throws FxApplicationException {
    Connection con = null;
    PreparedStatement ps = null;
    long count = 0;
    try {
        con = Database.getDbConnection();
        ps = con.prepareStatement("SELECT COUNT(*) FROM " + TBL_CONTENT_DATA + " WHERE FSELECT=?");
        ps.setLong(1, selectListItemId);
        ResultSet rs = ps.executeQuery();
        rs.next();
        count = rs.getLong(1);
        ps.close();
        if (EJBLookup.getDivisionConfigurationEngine().isFlatStorageEnabled()) {
            //also examine flat storage entries
            count += FxFlatStorageManager.getInstance().getSelectListItemInstanceCount(con, selectListItemId);
        }
    } catch (SQLException e) {
        throw new FxDbException(LOG, e, "ex.db.sqlError", e.getMessage());
    } finally {
        if (con != null)
            Database.closeObjects(SelectListEngineBean.class, con, ps);
    }
    return count;
}

From source file:com.tinyhydra.botd.sql.SQLInterface.java

public boolean SubmitVote(String username, String shop_id, int points, String shop_reference) {
    boolean addSuccess = false;

    GetShopDataAndAdd(shop_reference);/*from   w ww.j  a va  2 s.c  o  m*/

    PreparedStatement insertVoteStmt = null;

    String insertVoteQuery = qINSERT + qINTO + votesTable + " (" + votesUsernameField + "," + votesDateField
            + "," + votesShopVoteField + "," + votesPointsField + ") VALUES(?,?,?,?)";
    //+ qON + qDUPLICATE + qKEY + qUPDATE + votesShopVoteField + qEQUALS_VALUE;

    try {
        if (con == null || con.isClosed())
            con = new SQLConnector().getConnection();
        insertVoteStmt = con.prepareStatement(insertVoteQuery);

        insertVoteStmt.setString(1, username);
        insertVoteStmt.setLong(2, GetDate());
        insertVoteStmt.setString(3, shop_id);
        insertVoteStmt.setInt(4, points);

        insertVoteStmt.execute();

        addSuccess = true;

    } catch (SQLException sqe) {
        addSuccess = false;
        System.out.println(sqe);
    } finally {
        closeStatement(insertVoteStmt);
    }

    return addSuccess;
}

From source file:mysql5.MySQL5PlayerDAO.java

/**
 * {@inheritDoc} - KID/*  w ww .  j  a  va2  s.co  m*/
 */
@Override
public void setPlayerLastTransferTime(final int playerId, final long time) {
    DB.insertUpdate("UPDATE players SET last_transfer_time=? WHERE id=?", new IUStH() {
        @Override
        public void handleInsertUpdate(PreparedStatement stmt) throws SQLException {
            stmt.setLong(1, time);
            stmt.setInt(2, playerId);
            stmt.execute();
        }
    });
}

From source file:com.flexive.core.storage.genericSQL.GenericLockStorage.java

/**
 * Internal unlock method to unlock a primary key or resource
 *
 * @param con an open and valid connection
 * @param obj resource or primary key// ww w.  j a va  2  s . co m
 * @throws FxLockException on errors
 */
@SuppressWarnings({ "ThrowableInstanceNeverThrown" })
protected void _unlock(Connection con, Object obj) throws FxLockException {
    FxLock currentLock = _getLock(con, obj);
    if (!currentLock.isLocked())
        return; //nothing locked, so unlock is successful
    final UserTicket ticket = FxContext.getUserTicket();
    if (!ticket.isGlobalSupervisor() && (ticket.isGuest() || ticket.getUserId() == Account.USER_GUEST))
        throw new FxLockException("ex.lock.content.guest");
    final boolean allowUnlock = currentLock.getLockType() == FxLockType.Loose || currentLock.isExpired()
            || (currentLock.getLockType() == FxLockType.Permanent
                    && (ticket.getUserId() == currentLock.getUserId() || ticket.isGlobalSupervisor()
                            || ticket.isMandatorSupervisor()));
    if (!allowUnlock)
        throw new FxLockException("ex.lock.unlock.denied", obj);
    PreparedStatement ps = null;
    try {
        if (currentLock.isContentLock()) {
            obj = getDistinctPK(con, (FxPK) obj); //make sure to have a distinct pk
            ps = con.prepareStatement("DELETE FROM " + TBL_LOCKS + " WHERE LOCK_ID=? AND LOCK_VER=?");
            ps.setLong(1, ((FxPK) obj).getId());
            ps.setInt(2, ((FxPK) obj).getVersion());
        } else {
            ps = con.prepareStatement("DELETE FROM " + TBL_LOCKS + " WHERE LOCK_RESOURCE=?");
            ps.setString(1, String.valueOf(obj));
        }
        ps.executeUpdate();
    } catch (SQLException e) {
        throw new FxDbException(e, "ex.db.sqlError", e.getMessage()).asRuntimeException();
    } finally {
        Database.closeObjects(GenericLockStorage.class, null, ps);
    }
}

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

public void update(DocumentItem c, QueryRunner run, Connection conn) throws SQLException {
    PreparedStatement st = conn.prepareStatement(SQL_UPDATE_DOCUMENTITEM);
    st.setString(1, c.getPriceNetSingle());
    st.setString(2, c.getPriceGrossSingle());
    st.setString(3, c.getPriceTaxSingle());
    st.setString(4, c.getPriceNetAll());
    st.setString(5, c.getPriceGrossAll());
    st.setString(6, c.getPriceTaxAll());
    st.setString(7, c.getTaxValue());/*  w ww .  j  av  a2s . c o  m*/
    st.setString(8, c.getQuantity());
    if (c.getProduct().getId().longValue() == 0 && c.getDocument_id().longValue() == 0) {
        throw new SQLException(
                "For DocumentItem corresponding product and document it belongs to need to be specified");
    }
    if (c.getProduct().getId() != 0) {
        st.setLong(9, c.getProduct().getId());
    } else {
        st.setNull(9, java.sql.Types.NUMERIC);
    }
    if (c.getDocument_id().longValue() != 0) {
        st.setLong(10, c.getDocument_id());
    } else {
        st.setNull(10, java.sql.Types.NUMERIC);
    }
    st.setString(11, c.getProduct().getName());
    st.setLong(12, c.getId());
    // run the query
    int i = st.executeUpdate();
    System.out.println("i: " + i);
    if (i == -1) {
        System.out.println("db error : " + SQL_UPDATE_DOCUMENTITEM);
    }
}

From source file:gov.nih.nci.caarray.dao.ArrayDaoImpl.java

/**
 * {@inheritDoc}/*from  w w  w .  j  a  v  a 2 s  .  c o m*/
 */
@Override
public void createDesignElementListEntries(DesignElementList designElementList, int startIndex,
        List<Long> logicalProbeIds) {
    final Connection conn = getCurrentSession().connection();
    PreparedStatement stmt = null;
    try {
        stmt = conn.prepareStatement("insert into designelementlist_designelement "
                + "(designelementlist_id, designelement_id, designelement_index) values (?, ?, ?)");
        int i = startIndex;
        for (final Long probeId : logicalProbeIds) {
            stmt.setLong(1, designElementList.getId());
            stmt.setLong(2, probeId);
            stmt.setInt(3, i++);
            stmt.addBatch();
        }
        stmt.executeBatch();
    } catch (final SQLException e) {
        throw new DAOException("Error inserting elements in the design element list", e);
    } finally {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (final SQLException e) { // NOPMD - close quietly
                // close quietly
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (final SQLException e) { // NOPMD - close quietly
                // close quietly
            }
        }
    }
}

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

/**
 * {@inheritDoc}/*w  w w  .  jav a  2  s . co m*/
 */
@Override
public List<FxHistory> getEntries(String keyMatch, Long accountMatch, Long typeMatch, Long contentMatch,
        Date startDate, Date endDate, int maxEntries) {
    List<FxHistory> ret = new ArrayList<FxHistory>(100);
    Connection con = null;
    PreparedStatement ps = null;
    try {
        con = Database.getDbConnection();
        String query = "";
        if (accountMatch != null)
            query += " AND ACCOUNT=" + accountMatch;
        if (typeMatch != null)
            query += " AND TYPEID=" + typeMatch;
        if (contentMatch != null)
            query += " AND PKID=" + contentMatch;
        ps = con.prepareStatement(StorageManager.escapeReservedWords(HISTORY_SELECT)
                + " WHERE TIMESTP>=? AND TIMESTP<=? AND ACTION_KEY LIKE ? " + query + " ORDER BY TIMESTP DESC");
        ps.setLong(1, startDate == null ? 0 : startDate.getTime());
        ps.setLong(2, endDate == null ? Long.MAX_VALUE - 1 : endDate.getTime());
        ps.setString(3, (StringUtils.isEmpty(keyMatch) ? "" : keyMatch) + "%");
        ResultSet rs = ps.executeQuery();
        boolean loadData = FxContext.getUserTicket().isGlobalSupervisor();
        int count = 0;
        while (rs != null && rs.next()) {
            if (count++ >= maxEntries)
                break;
            long typeId = rs.getLong(8);
            if (rs.wasNull())
                typeId = -1;
            ret.add(new FxHistory(rs.getLong(3), rs.getLong(1), rs.getString(2), rs.getString(4),
                    rs.getString(5).split("\\|"), typeId, 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.webpagebytes.cms.local.WPBLocalDataStoreDao.java

private void setPrepareStatementParameter(PreparedStatement preparedStatement, int index, Object param)
        throws SQLException, WPBSerializerException {
    if (param.getClass().equals(Integer.class)) {
        preparedStatement.setInt(index, (Integer) param);
    } else if (param.getClass().equals(Long.class)) {
        preparedStatement.setLong(index, (Long) param);
    } else if (param.getClass().equals(String.class)) {
        preparedStatement.setString(index, (String) param);
    } else {// w w  w  . j a  v  a  2 s  . c  om
        throw new WPBSerializerException("Unsupported key type");
    }

}

From source file:com.ywang.alone.handler.task.AuthTask.java

/**
 * // w  w  w  .ja  va  2s.  c om
 * 
 * @param msg
 *            {
 *            'phoneNum':'ywang','password':'e10adc3949ba59abbe56e057f20f883
 *            e ' , 'deviceToken':'8a2597aa1d37d432a88a446d82b6561e',
 *            'lng':'117.157954','lat':'31.873432','osVersion':'8.0',
 *            'systemType':'iOS','phoneModel':'iPhone 5s','key':''}
 * 
 * @return
 */
private static JSONObject regNewUser(String msg) {
    JSONObject jsonObject = AloneUtil.newRetJsonObject();
    JSONObject user = JSON.parseObject(msg);
    DruidPooledConnection conn = null;
    PreparedStatement updatestmt = null;
    try {
        conn = DataSourceFactory.getInstance().getConn();
        conn.setAutoCommit(false);
        String uuid = UUID.randomUUID().toString();
        uuid = uuid.replaceAll("-", "");
        String token = MD5.getMD5String(uuid);

        String im_user = user.getString("phoneNum").trim();
        UserInfo userInfo = new UserInfo();
        userInfo.setRegTime(System.currentTimeMillis());
        userInfo.setOnline("1");
        userInfo.setKey(token);
        userInfo.setMessageUser(im_user);
        userInfo.setMessagePwd("alone123456");

        updatestmt = conn.prepareStatement(
                "insert into userbase (PHONE_NUM, PWD, REG_TIME, LNG, LAT, DEVICE_TOKEN, SYSTEM_TYPE, OS_VERSION,PHONE_MODEL, PKEY, MESSAGE_USER, MESSAGE_PWD) VALUES (?,?,?, ?,?,?,?,?,?,?,?,?)",
                Statement.RETURN_GENERATED_KEYS);
        updatestmt.setString(1, user.getString("phoneNum").trim());
        updatestmt.setString(2, user.getString("password").trim());
        updatestmt.setLong(3, userInfo.getRegTime());
        updatestmt.setString(4, user.getString("lng").trim());
        updatestmt.setString(5, user.getString("lat").trim());

        updatestmt.setString(6, user.getString("deviceToken").trim());
        updatestmt.setString(7, user.getString("systemType").trim());
        updatestmt.setString(8, user.getString("osVersion").trim());
        updatestmt.setString(9, user.getString("phoneModel").trim());
        updatestmt.setString(10, userInfo.getKey());
        updatestmt.setString(11, userInfo.getMessageUser());
        updatestmt.setString(12, "alone123456");

        int result = updatestmt.executeUpdate();

        if (result == 1) {
            ResultSet idRS = updatestmt.getGeneratedKeys();
            if (idRS.next()) {
                int userId = idRS.getInt(1);
                userInfo.setUserId(userId + "");
            }
            jsonObject.put("ret", Constant.RET.REG_SUCC);
            jsonObject.put("data", userInfo);
        } else {
            jsonObject.put("ret", Constant.RET.SYS_ERR);
            jsonObject.put("errCode", Constant.ErrorCode.SYS_ERR);
            jsonObject.put("errDesc", Constant.ErrorCode.SYS_ERR);
            LoggerUtil.logServerErr("insert into userbase no result");
        }

        conn.commit();
        conn.setAutoCommit(true);
    } catch (SQLException e) {
        LoggerUtil.logServerErr(e);
        jsonObject.put("ret", Constant.RET.SYS_ERR);
        jsonObject.put("errCode", Constant.ErrorCode.SYS_ERR);
        jsonObject.put("errDesc", Constant.ErrorCode.SYS_ERR);
    } finally {
        try {
            if (null != updatestmt) {
                updatestmt.close();
            }
            if (null != conn) {
                conn.close();
            }
        } catch (SQLException e) {
            LoggerUtil.logServerErr(e.getMessage());
        }
    }

    return jsonObject;
}