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:nl.surfnet.coin.teams.service.impl.TeamExternalGroupDaoImpl.java

private TeamExternalGroup mapRowToTeamExternalGroup(ResultSet rs) throws SQLException {
    ExternalGroup e = new ExternalGroup();
    e.setId(rs.getLong("eg_id"));
    e.setIdentifier(rs.getString(IDENTIFIER));
    e.setDescription(rs.getString(DESCRIPTION));
    e.setName(rs.getString(NAME));/*  w  ww.jav  a 2  s.c  o m*/
    e.setGroupProviderIdentifier(rs.getString(GROUP_PROVIDER));

    TeamExternalGroup teg = new TeamExternalGroup();
    teg.setId(rs.getLong("teg_id"));
    teg.setGrouperTeamId(rs.getString(GROUPER_TEAM_ID));
    teg.setExternalGroup(e);
    return teg;
}

From source file:com.oic.event.RegisterProfile.java

@Override
public void ActionEvent(JSONObject json, WebSocketListener webSocket) {
    JSONObject responseJSON = new JSONObject();
    responseJSON.put("method", "setprofile");
    if (!validation(json, webSocket)) {
        return;// www . j a v a2  s  . c  o m
    }
    Connection con = DatabaseConnection.getConnection();
    PreparedStatement ps;
    try {
        con = DatabaseConnection.getConnection();
        con.setAutoCommit(false);
        String sql = "INSERT INTO user SET studentnumber = ?, name = ?, avatarid = ?, grade = ?, sex = ?, birth = ?, comment = ?, secretkey = ?";
        ps = con.prepareStatement(sql);
        ps.setString(1, json.get("studentid").toString());
        ps.setString(2, json.get("username").toString());
        ps.setInt(3, Integer.parseInt(json.get("avatarid").toString()));
        ps.setInt(4, Integer.parseInt(json.get("grade").toString()));
        ps.setInt(5, Integer.parseInt(json.get("gender").toString()));
        ps.setDate(6, toDate(json.get("birthday").toString()));
        ps.setString(7, json.get("comment").toString());
        ps.setString(8, json.get("secretkey").toString());
        ps.executeUpdate();
        ps.close();

        sql = "SELECT last_insert_id() AS last";
        ps = con.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();
        if (!rs.next()) {
            throw new SQLException();
        }
        long userid = rs.getLong("last");
        rs.close();
        ps.close();

        sql = "INSERT INTO setting SET userid = ?, privategrade = ?, privatesex = ?, privatebirth = ?";
        ps = con.prepareStatement(sql);
        ps.setLong(1, userid);
        ps.setInt(2, Integer.parseInt(json.get("vgrade").toString()));
        ps.setInt(3, Integer.parseInt(json.get("vgender").toString()));
        ps.setInt(4, Integer.parseInt(json.get("vbirthday").toString()));
        ps.executeUpdate();
        ps.close();
        con.commit();

        responseJSON.put("status", 0);
        webSocket.userNoLogin();
    } catch (Exception e) {
        try {
            con.rollback();
        } catch (SQLException sq) {
            LOG.warning("[setProfile]Error Rolling back.");
        }
        e.printStackTrace();
        responseJSON.put("status", 1);
    } finally {
        try {
            con.setAutoCommit(true);
        } catch (SQLException ex) {
            Logger.getLogger(SetProfile.class.getName()).log(Level.WARNING,
                    "Error going back to AutoCommit mode", ex);
        }
    }
    webSocket.sendJson(responseJSON);
}

From source file:com.splicemachine.derby.utils.SpliceAdmin.java

/**
 * Be Careful when using this, as it will return conglomerate ids for all the indices of a table
 * as well as the table itself. While the first conglomerate SHOULD be the main table, there
 * really isn't a guarantee, and it shouldn't be relied upon for correctness in all cases.
 *//*from ww  w .  jav a 2  s.  c om*/
public static long[] getConglomNumbers(Connection conn, String schemaName, String tableName)
        throws SQLException {
    List<Long> conglomIDs = new ArrayList<>();
    if (schemaName == null)
        // default schema
        schemaName = SQLConfiguration.SPLICE_USER;

    String query;
    boolean isTableNameEmpty;

    if (tableName == null) {
        query = getSqlConglomsInSchema();
        isTableNameEmpty = true;
    } else {
        query = getSqlConglomsInTable();
        isTableNameEmpty = false;
    }

    ResultSet rs = null;
    PreparedStatement s = null;
    try {
        s = conn.prepareStatement(query);
        s.setString(1, schemaName.toUpperCase());
        if (!isTableNameEmpty) {
            s.setString(2, tableName.toUpperCase());
        }
        rs = s.executeQuery();
        while (rs.next()) {
            conglomIDs.add(rs.getLong(1));
        }

        if (conglomIDs.isEmpty()) {
            if (isTableNameEmpty) {
                throw PublicAPI
                        .wrapStandardException(ErrorState.LANG_SCHEMA_DOES_NOT_EXIST.newException(schemaName));
            }
            throw PublicAPI.wrapStandardException(ErrorState.LANG_TABLE_NOT_FOUND.newException(tableName));
        }
    } finally {
        if (rs != null)
            rs.close();
        if (s != null)
            s.close();
    }
    if (conglomIDs.isEmpty()) {
        return new long[0];
    }
    long[] congloms = new long[conglomIDs.size()];
    for (int i = 0; i < conglomIDs.size(); i++) {
        congloms[i] = conglomIDs.get(i);
    }
    /*
     * An index conglomerate id can be returned by the query before the main table one is,
    * but it should ALWAYS have a higher conglomerate id, so if we sort the congloms,
    * we should return the main table before any of its indices.
    */
    Arrays.sort(congloms);
    return congloms;
}

From source file:com.example.app.config.automation.ExampleAppDataConversionVersion1.java

/**
 * Example data conversion.//from   w w  w.  j ava 2s  .c  o  m
 *
 * @return data conversion.
 */
@Bean
@TaskQualifier(TaskQualifier.Type.data_conversion)
public DataConversion example2DataConversion() {
    final String[] signs = { "ARIES", "TAURUS", "GEMINI", "CANCER", "LEO", "VIRGO", "LIBRA", "SCORPIO",
            "SAGITTARIUS", "CAPRICORN", "AQUARIUS", "PISCES" };
    Arrays.sort(signs);

    final List<SQLStatement> preDDL = Collections.singletonList(
            new SQLStatement("CREATE TABLE Example_FOO(id serial, val text, primary key (id))", null));
    final List<SQLStatement> postDDL = Collections
            .singletonList(new SQLStatement("DROP TABLE Example_FOO;", null));
    return new AbstractDataConversion(IDENTIFIER, "Example Numero Dos", 2, true, null, preDDL, postDDL) {
        @Override
        @Nonnull
        public List<TaskArgument> getAdditionalArguments() {
            List<TaskArgument> args = new ArrayList<>();
            args.add(new TaskArgument(WHAT_S_YOUR_ZODIAC_SIGN, "", "Cancer", null));
            return args;
        }

        @Override
        public List<? extends SQLStatement> execute(TaskArgument[] arguments)
                throws SQLException, IllegalArgumentException {
            final SQLStatement stmt = new SQLStatement("INSERT INTO Example_Foo (val) VALUES (?)",
                    "Insert Sign");
            final Map<String, TaskArgument> argumentMapping = getArgumentMapping(arguments);
            stmt.setString(1, argumentMapping.get(WHAT_S_YOUR_ZODIAC_SIGN).getArgument().toString());
            return Collections.singletonList(stmt);
        }

        @Override
        public Map<TaskArgument, String> validateArguments(TaskArgument[] arguments) {
            final Map<TaskArgument, String> validationMap = new HashMap<>();
            final String sign = arguments[0].getArgument().toString().toUpperCase();
            final int foundIndex = Arrays.binarySearch(signs, sign);
            if (foundIndex < 0)
                validationMap.put(arguments[0], "That's not your sign fool.");
            return validationMap;
        }

        @Override
        public List<? extends SQLStatement> getValidationStatements() {
            return Collections.singletonList(new SQLStatement("SELECT COUNT(*) FROM Example_FOO", null));
        }

        @Override
        public String validateResult(SQLStatement stmt, int index, ResultSet result) throws SQLException {
            if (result.next()) {
                long count = result.getLong(1);
                return count == 1 ? null : "Received incorrect record count: " + count;
            } else
                return "Expecting Results";
        }
    };
}

From source file:de.ingrid.importer.udk.strategy.v331.IDCStrategy3_3_1_fixOrigId.java

private void fixObjectOrigId() throws Exception {
    log.info("\nFixing t01_object.org_obj_id...");

    PreparedStatement psUpdate = jdbc
            .prepareStatement("UPDATE t01_object SET " + "org_obj_id = NULL " + "WHERE id = ?");

    PreparedStatement psSelectObjs = jdbc.prepareStatement("SELECT id, obj_uuid, obj_name, create_time "
            + "FROM t01_object " + "WHERE org_obj_id = ? " + "ORDER BY create_time");

    // Fetch all OrigIds then process every ID and according objects
    Statement st = jdbc.createStatement();
    ResultSet rs = jdbc.executeQuery("SELECT distinct org_obj_id " + "FROM t01_object " + "ORDER BY org_obj_id",
            st);//from w w w. j a va  2  s.co m

    int numUpdated = 0;
    while (rs.next()) {
        String orgId = rs.getString("org_obj_id");

        // fetch all objects ordered by creation date (first one keeps origId, is the oldest one)
        psSelectObjs.setString(1, orgId);
        ResultSet rsSelectObjs = psSelectObjs.executeQuery();

        boolean firstObject = true;
        while (rsSelectObjs.next()) {
            long objId = rsSelectObjs.getLong("id");
            String objUuid = rsSelectObjs.getString("obj_uuid");
            String objName = rsSelectObjs.getString("obj_name");
            String objCreateTime = rsSelectObjs.getString("create_time");

            if (firstObject) {
                firstObject = false;
                log.info("KEEP org_obj_id '" + orgId + "' in OBJECT [id:" + objId + "/uuid:" + objUuid
                        + "/name:'" + objName + "'/createTime:" + objCreateTime + ") !");
                continue;
            }

            log.info("REMOVE org_obj_id '" + orgId + "' from OBJECT [id:" + objId + "/uuid:" + objUuid
                    + "/name:'" + objName + "'/createTime:" + objCreateTime + ") !");

            psUpdate.setLong(1, objId);
            psUpdate.executeUpdate();

            numUpdated++;
        }

        rsSelectObjs.close();
    }
    rs.close();
    st.close();
    psSelectObjs.close();
    psUpdate.close();

    log.info("Removed " + numUpdated + " Original Ids from objects");
    log.info("Fixing t01_object.org_obj_id... done\n");
}

From source file:tianci.pinao.dts.tasks.dao.impl.ConfigDaoImpl.java

@Override
public Map<Integer, Config> getConfigs() {
    final Map<Integer, Config> configs = new HashMap<Integer, Config>();
    getJdbcTemplate().query("select id, type, value, lastmod_time, lastmod_userid from "
            + SqlConstants.TABLE_CONFIG + " where isdel = ?", new Object[] { 0 }, new RowMapper<Config>() {

                @Override/*w  ww .  j  a va 2 s. c o m*/
                public Config mapRow(ResultSet rs, int index) throws SQLException {
                    Config config = new Config();

                    config.setId(rs.getInt("id"));
                    config.setType(rs.getInt("type"));
                    config.setValue(rs.getLong("value"));
                    Timestamp ts = rs.getTimestamp("lastmod_time");
                    if (ts != null)
                        config.setLastModTime(new Date(ts.getTime()));
                    config.setLastModUserid(rs.getInt("lastmod_userid"));

                    configs.put(config.getType(), config);

                    return config;
                }

            });

    return configs;
}

From source file:org.ulyssis.ipp.snapshot.Event.java

public void save(Connection connection) throws SQLException {
    if (id != -1)
        return;//w  w  w .j a va 2s  .c om
    try (PreparedStatement statement = connection.prepareStatement(
            "INSERT INTO \"events\" (\"time\",\"type\",\"data\",\"removed\") " + "VALUES (?,?,?,?)",
            Statement.RETURN_GENERATED_KEYS)) {
        statement.setTimestamp(1, Timestamp.from(time));
        String serialized;
        try {
            serialized = Serialization.getJsonMapper().writeValueAsString(this);
        } catch (JsonProcessingException e) {
            assert false;
            throw new IllegalStateException(e); // TODO(Roel): is this appropriate?
        }
        statement.setString(2, this.getClass().getSimpleName());
        statement.setString(3, serialized);
        statement.setBoolean(4, removed);
        statement.executeUpdate();
        ResultSet keys = statement.getGeneratedKeys();
        keys.next();
        this.id = keys.getLong(1);
    }
}

From source file:com.persistent.cloudninja.mapper.TenantUsageRowMapper.java

@Override
public Usage mapRow(ResultSet rs, int rowNum) throws SQLException {
    Usage usage = new Usage();
    usage.setTenantId(rs.getString("TenantId"));
    usage.setYear(rs.getInt("Year"));
    usage.setMonth(rs.getInt("Month"));
    usage.setDay(rs.getInt("Day"));
    usage.setDatabaseSize(rs.getLong("DatabaseSize"));
    usage.setDatabaseBandwidth_Ingress(rs.getLong("DatabaseBandwidth_Ingress"));
    usage.setDatabaseBandwidth_Egress(rs.getLong("DatabaseBandwidth_Egress"));
    usage.setWebAppBandwithUse_CS(rs.getLong("WebAppBandwithUse_CS"));
    usage.setWebAppBandwithUse_SC(rs.getLong("WebAppBandwithUse_SC"));
    usage.setWebAppRequests(rs.getLong("WebAppRequests"));
    usage.setBlobStoreUsage(rs.getLong("BlobStoreUsage"));
    usage.setTotalRequestPacketSize(rs.getLong("TotalRequestPacketSize"));
    usage.setTotalResponsePacketSize(rs.getLong("TotalResponsePacketSize"));
    usage.setTotalStorageTransactions(rs.getLong("TotalStorageTransactions"));
    return usage;
}

From source file:de.ingrid.importer.udk.strategy.v30.IDCStrategy3_0_1.java

protected void migrateSpatialSystem() throws Exception {
    if (log.isInfoEnabled()) {
        log.info("Migrate Spatial System to new table (now n:1)...");
    }/*w  w  w. j  ava  2  s. co  m*/

    // use PreparedStatement to avoid problems when value String contains "'" !!!
    String psSql = "INSERT INTO spatial_system (id, obj_id, line, referencesystem_key, referencesystem_value) "
            + "VALUES (?, ?, 1, ?, ?)";

    PreparedStatement ps = jdbc.prepareStatement(psSql);

    String sql = "select distinct id, obj_id, referencesystem_key, referencesystem_value "
            + "from t011_obj_geo";

    Statement st = jdbc.createStatement();
    ResultSet rs = jdbc.executeQuery(sql, st);
    int numMigrated = 0;
    while (rs.next()) {
        long objId = rs.getLong("obj_id");
        int referencesystemKey = rs.getInt("referencesystem_key");
        String referencesystemValue = rs.getString("referencesystem_value");

        if (referencesystemKey == 0) {
            referencesystemKey = -1;
        }
        if (referencesystemKey > 0 || referencesystemValue != null) {
            ps.setLong(1, getNextId());
            ps.setLong(2, objId);
            ps.setInt(3, referencesystemKey);
            ps.setString(4, referencesystemValue);
            ps.executeUpdate();

            numMigrated++;

            if (log.isDebugEnabled()) {
                log.debug("Migrated spatial system (key:" + referencesystemKey + ", value:'"
                        + referencesystemValue + "') of object with id:" + objId + ").");
            }
        }
    }
    rs.close();
    st.close();
    ps.close();

    if (log.isDebugEnabled()) {
        log.debug("Migrated " + numMigrated + " spatial systems.");
    }

    if (log.isInfoEnabled()) {
        log.info("Migrate Spatial System to new table (now n:1)... done");
    }
}

From source file:henu.dao.impl.CaclDaoImpl.java

@Override
public Cacl getCacl(String cid) {
    String sql = "select * from cacl where cid=" + cid;

    ResultSet rs = SqlDB.executeQuery(sql);
    Cacl cacl = new Cacl();

    try {//www.  j a  va2s. c o m
        cacl.setTid(rs.getLong("cid"));
        cacl.setName(rs.getString("cname"));
        cacl.setStructure(rs.getString("structure"));
        cacl.setAuthor(rs.getInt("author"));
        cacl.setType(rs.getBoolean("ctype"));
        cacl.setPostime(rs.getTimestamp("postime").toString());
        cacl.setEndtime(rs.getString("endtime"));
        cacl.setUsers(getCaclUserList(cid));

    } catch (SQLException ex) {
        Logger.getLogger(CaclDaoImpl.class.getName()).log(Level.SEVERE, null, ex);
    }

    SqlDB.close();

    return cacl;
}