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.ywang.alone.handler.task.AuthTask.java

/**
 *  { 'key':'2597aa1d37d432a','fid':'1020293' }
 * /*from   w  w  w  . j a va  2 s . co  m*/
 * @param param
 * @return
 */
private static String follow(String msg) {
    JSONObject jsonObject = AloneUtil.newRetJsonObject();
    JSONObject param = JSON.parseObject(msg);
    String token = param.getString("key");
    String userId = null;

    if (StringUtils.isEmpty(token)) {
        jsonObject.put("ret", Constant.RET.NO_ACCESS_AUTH);
        jsonObject.put("errCode", Constant.ErrorCode.NO_ACCESS_AUTH);
        jsonObject.put("errDesc", Constant.ErrorDesc.NO_ACCESS_AUTH);
        return jsonObject.toJSONString();
    }

    Jedis jedis = JedisUtil.getJedis();
    Long tokenTtl = jedis.ttl("TOKEN:" + token);
    if (tokenTtl == -1) {
        jsonObject.put("ret", Constant.RET.NO_ACCESS_AUTH);
        jsonObject.put("errCode", Constant.ErrorCode.NO_ACCESS_AUTH);
        jsonObject.put("errDesc", Constant.ErrorDesc.NO_ACCESS_AUTH);
    } else {
        userId = jedis.get("TOKEN:" + token);
        LoggerUtil.logMsg("uid is " + userId);
    }

    JedisUtil.returnJedis(jedis);

    if (StringUtils.isEmpty(userId)) {
        jsonObject.put("ret", Constant.RET.NO_ACCESS_AUTH);
        jsonObject.put("errCode", Constant.ErrorCode.NO_ACCESS_AUTH);
        jsonObject.put("errDesc", Constant.ErrorDesc.NO_ACCESS_AUTH);
        return jsonObject.toJSONString();
    }

    DruidPooledConnection conn = null;
    PreparedStatement stmt = null;
    try {
        conn = DataSourceFactory.getInstance().getConn();

        conn.setAutoCommit(false);

        stmt = conn.prepareStatement("insert into follow (USER_ID, FOLLOWED_ID, `TIME`) VALUES (?,?,?)",
                Statement.RETURN_GENERATED_KEYS);
        stmt.setString(1, userId);
        stmt.setString(2, param.getString("fid").trim());
        stmt.setLong(3, System.currentTimeMillis());

        int result = stmt.executeUpdate();
        if (result != 1) {

            jsonObject.put("ret", Constant.RET.UPDATE_DB_FAIL);
            jsonObject.put("errCode", Constant.ErrorCode.UPDATE_DB_FAIL);
            jsonObject.put("errDesc", Constant.ErrorDesc.UPDATE_DB_FAIL);
        }

        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.ErrorDesc.SYS_ERR);
    } finally {
        try {
            if (null != stmt) {
                stmt.close();
            }
            if (null != conn) {
                conn.close();
            }
        } catch (SQLException e) {
            LoggerUtil.logServerErr(e.getMessage());
        }
    }

    return jsonObject.toJSONString();
}

From source file:com.senior.g40.service.UserService.java

public boolean createUser(String username, String password, char userType) throws SQLException {
    Connection conn = ConnectionBuilder.getConnection();
    String sqlCmd = "INSERT INTO `user` (`userId`, `username`, `password`, `userType`) VALUES (?, ?, ?, ?);";
    PreparedStatement pstm = conn.prepareStatement(sqlCmd);
    pstm.setLong(1, getLatestUserId());
    pstm.setString(2, username);//from  w  w w .  j  a  v  a 2 s.  c om
    pstm.setString(3, Encrypt.toMD5(password));
    pstm.setString(4, String.valueOf(userType));
    if (pstm.executeUpdate() != 0) {
        conn.close();
        return true;
    } else {
        conn.close();
        return false;
    }
}

From source file:dao.CarryonBlobUpdate.java

/**
* This method is used to add blobstreams for a user. <code>Userpage</code>
* @param blob - the blob stream//from   w w w.  j a v a  2  s . c  o m
* @param category - 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 loginId - the loginId
* @param bsize - the size of the blob
* @param zoom - the zoom for the blob (used for displaying for image/jpeg)
* @throws Dao Exception - when an error or exception occurs while inserting this blob in DB.
*
 **/
public void run(Connection conn, byte[] blob, int category, String mimeType, String btitle, String loginId,
        long bsize, int zoom, String caption) throws BaseDaoException {

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

    //long dt = System.currentTimeMillis();
    // Connection conn = null;
    String stmt = "insert into carryon values(?, ?, ?, ?, ?, CURRENT_TIMESTAMP(), ?, ?, ?, ?, ?)";
    PreparedStatement s = null;
    try {
        //    conn = dataSource.getConnection();
        s = conn.prepareStatement(stmt);
        s.setLong(1, 0); // entryid
        s.setLong(2, new Long(loginId)); // loginid
        s.setInt(3, new Integer(category)); // category
        s.setString(4, mimeType); // mimetype
        s.setString(5, btitle); // btitle
        // s.setDate(6, new Date(dt));
        // s.setDate(6, CURRENT_TIMESTAMP());
        s.setBytes(6, blob);
        s.setLong(7, bsize);
        s.setInt(8, new Integer(zoom));
        s.setInt(9, 0); // hits
        s.setBytes(10, capBytes); // caption
        s.executeUpdate();
    } catch (SQLException e) {
        logger.error("Error adding a blob.", e);
        throw new BaseDaoException("Error adding a blob " + e.getMessage(), e);
    }
}

From source file:com.keybox.manage.db.PublicKeyDB.java

/**
 * updates existing public key//from  w ww.ja va  2 s .  c  o m
 *
 * @param publicKey key object
 */
public static void updatePublicKey(PublicKey publicKey) {

    Connection con = null;
    try {
        con = DBUtils.getConn();
        PreparedStatement stmt = con.prepareStatement(
                "update public_keys set key_nm=?, type=?, fingerprint=?, public_key=?, profile_id=? where id=? and user_id=? and enabled=true");
        stmt.setString(1, publicKey.getKeyNm());
        stmt.setString(2, SSHUtil.getKeyType(publicKey.getPublicKey()));
        stmt.setString(3, SSHUtil.getFingerprint(publicKey.getPublicKey()));
        stmt.setString(4, publicKey.getPublicKey().trim());
        if (publicKey.getProfile() == null || publicKey.getProfile().getId() == null) {
            stmt.setNull(5, Types.NULL);
        } else {
            stmt.setLong(5, publicKey.getProfile().getId());
        }
        stmt.setLong(6, publicKey.getId());
        stmt.setLong(7, publicKey.getUserId());
        stmt.execute();
        DBUtils.closeStmt(stmt);

    } catch (Exception e) {
        log.error(e.toString(), e);
    }
    DBUtils.closeConn(con);

}

From source file:net.sf.l2j.gameserver.model.entity.ClanHallSiege.java

public void setNewSiegeDate(long siegeDate, int ClanHallId, int hour) {
    Calendar tmpDate = Calendar.getInstance();
    if (siegeDate <= System.currentTimeMillis()) {
        tmpDate.setTimeInMillis(System.currentTimeMillis());
        tmpDate.add(Calendar.DAY_OF_MONTH, 3);
        tmpDate.set(Calendar.DAY_OF_WEEK, 6);
        tmpDate.set(Calendar.HOUR_OF_DAY, hour);
        tmpDate.set(Calendar.MINUTE, 0);
        tmpDate.set(Calendar.SECOND, 0);
        setSiegeDate(tmpDate);/*from   w ww.j a  v a 2s  .  c o m*/
        Connection con = null;
        try {
            con = L2DatabaseFactory.getInstance().getConnection();
            PreparedStatement statement = con
                    .prepareStatement("UPDATE clanhall_siege SET siege_data=? WHERE id = ?");
            statement.setLong(1, getSiegeDate().getTimeInMillis());
            statement.setInt(2, ClanHallId);
            statement.execute();
            statement.close();
        } catch (Exception e) {
            _log.error("Exception: can't save clanhall siege date: " + e.getMessage(), e);
        } finally {
            try {
                if (con != null)
                    con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.starit.diamond.server.service.DBPersistService.java

public void removeConfigInfoByID(final long id) {

    this.jt.update("delete from config_info where ID=? ", new PreparedStatementSetter() {
        public void setValues(PreparedStatement ps) throws SQLException {
            ps.setLong(1, id);
        }//from w w w  . j av a2s  . c  om

    });
}

From source file:com.onclave.testbench.jdbcTemplate.DAOSupport.StudentDAOImplementation.java

@Override
public boolean deleteStudent(final long idStudent) {
    final int result = jdbcTemplate.update(new PreparedStatementCreator() {
        @Override/*  ww w .  ja  v  a 2  s.c  o m*/
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement preparedStatement = connection
                    .prepareStatement(QueryStatements.DELETE_STUDENT_BY_ID_SQL);
            preparedStatement.setLong(1, idStudent);

            return preparedStatement;
        }
    });

    if (result > 0) {
        return true;
    }

    return false;
}

From source file:com.winterfarmer.virgo.vehicle.dao.VehicleMysqlDaoImpl.java

private PreparedStatement createInsertPreparedStatement(Connection connection, final Vehicle vehicle)
        throws SQLException {
    VirgoLogger.info(insert_vehicle_sql);
    PreparedStatement ps = connection.prepareStatement(insert_vehicle_sql,
            new String[] { vehicleId.getName() });
    ps.setLong(1, vehicle.getUserId());
    ps.setString(2, vehicle.getLicensePlate());
    ps.setString(3, vehicle.getVehicleIdNo());
    ps.setString(4, vehicle.getEngineNo());
    ps.setInt(5, vehicle.getState().getIndex());
    setExtForPreparedStatement(ps, 6, vehicle.getProperties());
    return ps;//  ww w.jav a  2 s  .c  o m
}

From source file:com.mtgi.analytics.sql.BehaviorTrackingDataSourceTest.java

@Test
public void testPreparedStatement() throws Exception {
    //test tracking through the prepared statement API, which should also
    //log parameters in the events.
    PreparedStatement stmt = conn.prepareStatement("insert into TEST_TRACKING values (?, ?, ?)");
    stmt.setLong(1, 1);
    stmt.setString(2, "hello");
    stmt.setObject(3, null, Types.VARCHAR);
    assertEquals(1, stmt.executeUpdate());

    //test support for batching.  each batch should log 1 event.
    stmt.setLong(1, 3);//  w w  w  .j  a va 2 s.c o  m
    stmt.setString(2, "batch");
    stmt.setObject(3, "1", Types.VARCHAR);
    stmt.addBatch();

    stmt.setLong(1, 4);
    stmt.setString(2, "batch");
    stmt.setObject(3, "2", Types.VARCHAR);
    stmt.addBatch();
    stmt.executeBatch();

    //back to a regular old update.
    stmt.setLong(1, 2);
    stmt.setObject(2, "goodbye", Types.VARCHAR);
    stmt.setNull(3, Types.VARCHAR);
    assertEquals(1, stmt.executeUpdate());

    stmt = conn.prepareStatement("update TEST_TRACKING set DESCRIPTION = 'world'");
    assertEquals(4, stmt.executeUpdate());

    stmt = conn.prepareStatement("select ID from TEST_TRACKING order by ID");
    ResultSet rs = stmt.executeQuery();
    int index = 0;
    long[] keys = { 1L, 2L, 3L, 4L };
    while (rs.next())
        assertEquals(keys[index++], rs.getLong(1));
    rs.close();
    assertEquals(4, index);

    manager.flush();
    assertEventDataMatches("BehaviorTrackingDataSourceTest.testPreparedStatement-result.xml");
}

From source file:bq.jpa.demo.query.nativequery.service.NativeQueryService.java

/**
 * use jdbc directly/*w ww.  j ava 2  s.c  o  m*/
 */
public void doJDBCQuery() {
    Connection conn = null;
    PreparedStatement ps = null;

    try {
        conn = ds.getConnection();
        ps = conn.prepareStatement(EMPLOYEE_QUERY);
        ps.setLong(1, 1500);
        ResultSet rs = ps.executeQuery();

        List<Employee> employees = new ArrayList<>();
        while (rs.next()) {
            Employee employee = new Employee();
            employee.setId(rs.getInt("pk_employee"));
            employee.setName(rs.getString("name"));
            employee.setSalary(rs.getInt("salary"));
            employees.add(employee);
        }

        ResultViewer.showResult(employees, EMPLOYEE_QUERY);
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            ps.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

}