Example usage for java.sql ResultSet getLong

List of usage examples for java.sql ResultSet getLong

Introduction

In this page you can find the example usage for java.sql ResultSet getLong.

Prototype

long getLong(String columnLabel) throws SQLException;

Source Link

Document

Retrieves the value of the designated column in the current row of this ResultSet object as a long in the Java programming language.

Usage

From source file:io.spring.batch.domain.CustomerRowMapper.java

@Override
public Customer mapRow(ResultSet resultSet, int i) throws SQLException {
    return new Customer(resultSet.getLong("id"), resultSet.getString("firstName"),
            resultSet.getString("lastName"), resultSet.getDate("birthdate"));
}

From source file:com.flexive.core.Database.java

/**
 * Loads all FxString entries stored in the given table.
 *
 * @param con     an existing connection
 * @param table   table to use/*from   w w  w.  j  a va2 s  .  c o  m*/
 * @param columns name of the columns containing the translations
 * @return all FxString entries stored in the given table, indexed by the ID field.
 * @throws SQLException if the query was not successful
 */
public static Map<Long, FxString[]> loadFxStrings(Connection con, String table, String... columns)
        throws SQLException {
    Statement stmt = null;
    final StringBuilder sql = new StringBuilder();
    final Map<Long, FxString[]> result = Maps.newHashMap();
    final Map<String, String> cache = Maps.newHashMap(); // avoid return duplicate strings
    try {
        sql.append("SELECT ID, LANG");
        final boolean hasDefLang = columns.length == 1; // deflang is only meaningful for single-column tables
        if (hasDefLang)
            sql.append(", DEFLANG");
        for (String column : columns) {
            sql.append(',').append(column);
            if (!hasDefLang)
                sql.append(',').append(column).append("_MLD");
        }
        sql.append(" FROM ").append(table).append(ML).append(" ORDER BY LANG");
        final int startIndex = hasDefLang ? 4 : 3;
        stmt = con.createStatement();
        final ResultSet rs = stmt.executeQuery(sql.toString());
        while (rs.next()) {
            final long id = rs.getLong(1);
            final int lang = rs.getInt(2);
            boolean defLang = false;
            if (hasDefLang)
                defLang = rs.getBoolean(3);
            if (lang == FxLanguage.SYSTEM_ID) {
                continue; // TODO how to deal with system language? 
            }
            FxString[] entry = result.get(id);
            if (entry == null) {
                entry = new FxString[columns.length];
            }
            for (int i = 0; i < columns.length; i++) {
                final String value = rs.getString(startIndex + i * (hasDefLang ? 1 : 2));
                String translation = cache.get(value); // return cached string instance
                if (translation == null) {
                    translation = value;
                    cache.put(value, value);
                }
                if (entry[i] == null)
                    entry[i] = new FxString(true, lang, translation);
                else
                    entry[i].setTranslation(lang, translation);
                if (!hasDefLang)
                    defLang = rs.getBoolean(startIndex + 1 + i * 2);
                if (defLang)
                    entry[i].setDefaultLanguage(lang);
            }
            result.put(id, entry);
        }

        // canonicalize FxStrings (some tables, especially assignments, contain a lot of 100% identical labels for different IDs)
        final Map<FxString, FxString> fxCache = Maps.newHashMapWithExpectedSize(result.size() * 2);
        for (FxString[] values : result.values()) {
            for (int i = 0; i < values.length; i++) {
                final FxString value = values[i];
                FxString cached = fxCache.get(value);
                if (cached != null) {
                    values[i] = cached;
                } else {
                    fxCache.put(value, value);
                }
            }
        }
    } finally {
        closeObjects(Database.class, null, stmt);
    }
    return result;
}

From source file:edu.lafayette.metadb.model.userman.UserManDAO.java

/**
 * Get a user's data.//from  w  w w . j  av  a 2  s.  c  o m
 * 
 * @param userName The username of the desired user.    
 * @return a User object with username, password and type for the requested user.
 * 
 */
public static User getUserData(String userName) {
    User requestedUser = null; // initialize return object

    Connection conn = Conn.initialize(); // Establish connection
    if (conn != null) {
        try {
            if (!MetaDbHelper.userExists(userName)) // If user doesn't exist
                return new User("", "", "", "", 0, ""); //Return a dummy user
            PreparedStatement getUserQuery = conn.prepareStatement(GET_USER_DATA);

            getUserQuery.setString(1, userName); // set parameter
            ResultSet userData = getUserQuery.executeQuery();

            if (userData != null) // The query result was not null
            {
                userData.next();
                // Get parameters
                String password = userData.getString(Global.USER_PASSWORD);
                String type = userData.getString(Global.USER_TYPE);
                String authType = userData.getString(Global.USER_AUTH_TYPE);
                long last_login = userData.getLong(Global.USER_LAST_LOGIN);
                String lastProj = userData.getString(Global.USER_LAST_ACCESS);
                requestedUser = new User(userName, password, type, authType, last_login, lastProj);

            }

            getUserQuery.close();
            userData.close();

            conn.close();
        } catch (Exception e) {
            MetaDbHelper.logEvent(e);
        }
    }
    return requestedUser;
}

From source file:ch.iceage.icedms.persistence.jdbc.rowmapper.AbstractGenericRowMapper.java

@Override
public void mapRowId(Identity id, String tableAlias, ResultSet rs, int rowNum) throws SQLException {
    id.setId(rs.getLong("id"));
}

From source file:at.alladin.rmbt.db.fields.LongField.java

@Override
public void setField(final ResultSet rs) throws SQLException {
    value = rs.getLong(dbKey);
    if (rs.wasNull())
        value = null;/*from  w  ww.j a  v  a2s . co m*/
}

From source file:dk.netarkivet.common.utils.DBUtils.java

/**
 * Get a Long from the resultSet in column i.
 * @param rs the resultset//from   w  ww  .j  a v a2 s  .  c  o m
 * @param i the column where the wanted Long resides
 * @return a Long object located in column i in the resultset
 * @throws SQLException If the columnIndex is not valid, or a database
 * access error occurs or this method is called on a closed result set
 */
public static Long getLongMaybeNull(ResultSet rs, int i) throws SQLException {
    ArgumentNotValid.checkNotNull(rs, "ResultSet rs");
    Long res = rs.getLong(i);
    if (rs.wasNull()) {
        return null;
    }
    return res;
}

From source file:org.openmrs.module.bahmniexports.example.domain.trade.internal.TradeRowMapper.java

@Override
public Trade mapRow(ResultSet rs, int rowNum) throws SQLException {
    Trade trade = new Trade(rs.getLong(ID_COLUMN));

    trade.setIsin(rs.getString(ISIN_COLUMN));
    trade.setQuantity(rs.getLong(QUANTITY_COLUMN));
    trade.setPrice(rs.getBigDecimal(PRICE_COLUMN));
    trade.setCustomer(rs.getString(CUSTOMER_COLUMN));
    trade.setVersion(rs.getInt(VERSION_COLUMN));

    return trade;
}

From source file:entity.mapper.DepartemenMapper.java

@Override
public Departemen mapRow(ResultSet rs, int i) throws SQLException {
    Departemen temp = new Departemen();
    temp.setId(rs.getLong("id"));
    temp.setKode(rs.getString("kode"));
    temp.setNama(rs.getString("nama"));
    return temp;/*from  w  ww .  ja v a2  s . com*/
}

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

/**
 *  /*from  ww  w  .ja  v  a  2s. c  o m*/
 * 
 * @param param
 * 
 *            {
 *            'phoneNum':'ywang','password':'e10adc3949ba59abbe56e057f20f883
 *            e ','lng':'117.157954','lat':'31.873432',
 *            'deviceToken':'8a2597aa1d37d432a88a446d82b6561e','osVersion':'
 *            8 . 0 ' , 'systemType':'iOS','phoneModel':'iPhone 5s'}
 * 
 *            OR
 * 
 *            {'key':'2597aa1d37d432a','lng':'117.157954','lat':'31.873432',
 *            'deviceToken':'8a2597aa1d37d432a88a446d82b6561e','osVersion':'
 *            8 . 0 ' , 'systemType':'iOS','phoneModel':'iPhone 5s'}
 * 
 * @return {"data":{"key":"e1e10c1ba704d1f10acda309138a2153","messagePwd":
 *         "alone123456"
 *         ,"messageUser":"15256551134324","online":"1","regTime"
 *         :1415177594592,"userId":"23"},"errCode":0,"errDesc":"","ret":5}
 */
private static String login(String msg) {
    JSONObject jsonObject = AloneUtil.newRetJsonObject();
    JSONObject user = JSON.parseObject(msg);

    DruidPooledConnection conn = null;
    PreparedStatement stmt = null;
    try {
        conn = DataSourceFactory.getInstance().getConn();
        conn.setAutoCommit(false);
        String token = user.getString("key");
        String userId = null;
        boolean needUpdateToken = false;

        if (StringUtils.isEmpty(token)) {// ???
            needUpdateToken = true;
            String uuid = UUID.randomUUID().toString();
            uuid = uuid.replaceAll("-", "");
            token = MD5.getMD5String(uuid);

            stmt = conn.prepareStatement("SELECT * FROM userbase WHERE PHONE_NUM = ? AND PWD = ? ");
            stmt.setString(1, user.getString("phoneNum"));
            stmt.setString(2, user.getString("password"));

        } else {//  token 
            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 + "")) {
                return jsonObject.toJSONString();
            }
            stmt = conn.prepareStatement("SELECT * FROM userbase WHERE user_id = ?");
            stmt.setString(1, userId + "");
        }

        ResultSet rs = stmt.executeQuery();
        if (rs.next()) { // 
            UserInfo userInfo = new UserInfo();
            userId = rs.getString("USER_ID");
            userInfo.setRegTime(rs.getLong("REG_TIME"));
            userInfo.setUserId(userId + "");
            userInfo.setAvatar(rs.getString("AVATAR"));
            userInfo.setNickName(rs.getString("NICKNAME"));
            userInfo.setAge(rs.getString("AGE"));
            userInfo.setHoroscope(rs.getString("HORO_SCOPE"));
            userInfo.setHeight(rs.getString("HEIGHT"));
            userInfo.setWeight(rs.getString("WEIGHT"));
            userInfo.setRoleName(rs.getString("ROLENAME"));
            userInfo.setAffection(rs.getString("AFFECTION"));
            userInfo.setPurpose(rs.getString("PURPOSE"));
            userInfo.setEthnicity(rs.getString("ETHNICITY"));
            userInfo.setOccupation(rs.getString("OCCUPATION"));
            userInfo.setLivecity(rs.getString("LIVECITY"));
            userInfo.setLocation(rs.getString("LOCATION"));
            userInfo.setTravelcity(rs.getString("TRAVELCITY"));
            userInfo.setMovie(rs.getString("MOVIE"));
            userInfo.setMusic(rs.getString("MUSIC"));
            userInfo.setBooks(rs.getString("BOOKS"));
            userInfo.setFood(rs.getString("FOOD"));
            userInfo.setOthers(rs.getString("OTHERS"));
            userInfo.setIntro(rs.getString("INTRO"));
            userInfo.setMessagePwd(rs.getString("MESSAGE_PWD"));
            userInfo.setMessageUser(rs.getString("MESSAGE_USER"));
            userInfo.setKey(token);
            userInfo.setOnline("1");

            jsonObject.put("data", JSONObject.toJSON(userInfo));

            // token ?
            PreparedStatement updatestmt = null;
            if (needUpdateToken) {
                updatestmt = conn.prepareStatement(
                        "update userbase set PKEY = ?, LAST_LOGIN_TIME = ? , OS_VERSION=? , SYSTEM_TYPE=? , PHONE_MODEL=? , DEVICE_TOKEN=? , LNG=? , LAT=? , ONLINE='1' WHERE USER_ID=?");
                updatestmt.setString(1, token);
                updatestmt.setLong(2, System.currentTimeMillis());
                updatestmt.setString(3, user.getString("osVersion"));
                updatestmt.setString(4, user.getString("systemType"));
                updatestmt.setString(5, user.getString("phoneModel"));
                updatestmt.setString(6, user.getString("deviceToken"));
                updatestmt.setString(7, user.getString("lng"));
                updatestmt.setString(8, user.getString("lat"));
                updatestmt.setString(9, userInfo.getUserId());
            } else {
                updatestmt = conn.prepareStatement(
                        "update userbase set LAST_LOGIN_TIME = ? , LNG=? , LAT=? , OS_VERSION=? , SYSTEM_TYPE=? , PHONE_MODEL=? , DEVICE_TOKEN= ? , ONLINE='1'  WHERE USER_ID=?");
                updatestmt.setLong(1, System.currentTimeMillis());
                updatestmt.setString(2, user.getString("lng"));
                updatestmt.setString(3, user.getString("lat"));
                updatestmt.setString(4, user.getString("osVersion"));
                updatestmt.setString(5, user.getString("systemType"));
                updatestmt.setString(6, user.getString("phoneModel"));
                updatestmt.setString(7, user.getString("deviceToken"));
                updatestmt.setString(8, userInfo.getUserId());
            }
            int result = updatestmt.executeUpdate();

            if (result != 1) {
                jsonObject.put("ret", Constant.RET.TOKEN_UPDATE_FAIL);
                jsonObject.put("errCode", Constant.ErrorCode.TOKEN_UPDATE_FAIL);
                jsonObject.put("errDesc", Constant.ErrorDesc.TOKEN_UPDATE_FAIL);
            }
            updatestmt.close();
        }
        // 
        else {
            jsonObject = regNewUser(msg);
            JSONObject data = jsonObject.getJSONObject("data");
            userId = data.getString("userId");
            token = data.getString("key");
            LoggerUtil.logMsg("register succ userId is: " + userId + " token is " + token);
        }

        rs.close();
        conn.commit();
        conn.setAutoCommit(true);

        //redis
        Jedis jedis = JedisUtil.getJedis();
        //
        jedis.setex("TOKEN:" + token, 86400 * 14, userId + "");
        JedisUtil.returnJedis(jedis);

    } 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:net.mindengine.oculus.frontend.service.user.UserMapper.java

@Override
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
    User user = new User();
    user.setId(rs.getLong("id"));
    user.setLogin(rs.getString("login"));
    user.setPassword(rs.getString("password"));
    user.setName(rs.getString("name"));
    return user;//w  w w  .java2  s  .  co m
}