Example usage for java.sql ResultSet getString

List of usage examples for java.sql ResultSet getString

Introduction

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

Prototype

String getString(String columnLabel) throws SQLException;

Source Link

Document

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

Usage

From source file:jongo.handler.JongoResultSetHandler.java

/**
 * Converts a ResultSet to a Map. Important to note that DATE, TIMESTAMP & TIME objects generate
 * a {@linkplain org.joda.time.DateTime} object using {@linkplain org.joda.time.format.ISODateTimeFormat}.
 * @param resultSet a {@linkplain java.sql.ResultSet}
 * @return a Map with the column names as keys and the values. null if something goes wrong.
 *//*from  ww  w . j  a  v  a2 s .  c  om*/
public static Map<String, String> resultSetToMap(ResultSet resultSet) {
    Map<String, String> map = new HashMap<String, String>();
    try {
        int columnCount = resultSet.getMetaData().getColumnCount();

        l.trace("Mapping a result set with " + columnCount + " columns to a Map");

        ResultSetMetaData meta = resultSet.getMetaData();
        for (int i = 1; i < columnCount + 1; i++) {
            String colName = meta.getColumnName(i).toLowerCase();
            int colType = meta.getColumnType(i);
            String v = resultSet.getString(i);
            if (colType == Types.DATE) {
                v = new DateTime(resultSet.getDate(i)).toString(dateFTR);
                l.trace("Mapped DATE column " + colName + " with value : " + v);
            } else if (colType == Types.TIMESTAMP) {
                v = new DateTime(resultSet.getTimestamp(i)).toString(dateTimeFTR);
                l.trace("Mapped TIMESTAMP column " + colName + " with value : " + v);
            } else if (colType == Types.TIME) {
                v = new DateTime(resultSet.getTimestamp(i)).toString(timeFTR);
                l.trace("Mapped TIME column " + colName + " with value : " + v);
            } else {
                l.trace("Mapped " + meta.getColumnTypeName(i) + " column " + colName + " with value : " + v);
            }
            map.put(colName, v);
        }
    } catch (SQLException e) {
        l.error("Failed to map ResultSet");
        l.error(e.getMessage());
        return null;
    }

    return map;
}

From source file:edu.jhu.pha.vospace.storage.SwiftStorageManager.java

public static String generateRandomCredentials(final String username) {
    return DbPoolServlet.goSql("Generate random credentials",
            "select username, apikey from storage_users_pool where user_id IS NULL limit 1;",
            new SqlWorker<String>() {
                @Override/*from   w  w w . j a va2 s.  co  m*/
                public String go(Connection conn, PreparedStatement stmt) throws SQLException {
                    ResultSet rs = stmt.executeQuery();
                    if (rs.next()) {
                        String user = rs.getString("username");
                        String password = rs.getString("apikey");
                        PreparedStatement prep = conn.prepareStatement(
                                "update storage_users_pool SET user_id = (select user_id from user_identities where identity = ?) where username = ?");
                        prep.setString(1, username);
                        prep.setString(2, user);
                        prep.execute();

                        logger.debug(username + " " + user);

                        StringWriter writer = new StringWriter();
                        JsonFactory f = new JsonFactory();
                        try {
                            JsonGenerator g = f.createJsonGenerator(writer);

                            g.writeStartObject();
                            g.writeStringField("username", user);
                            g.writeStringField("apikey", password);
                            g.writeEndObject();

                            g.close(); // important: will force flushing of output, close underlying output stream

                            return writer.getBuffer().toString();
                        } catch (JsonGenerationException ex) {
                            throw new InternalServerErrorException(
                                    "Error generating user storage credentials. " + ex.getMessage());
                        } catch (IOException e) {
                            throw new InternalServerErrorException(
                                    "Error generating user storage credentials. " + e.getMessage());
                        }

                    } else
                        throw new PermissionDeniedException("The user does not exist.");
                }
            });

}

From source file:com.wso2telco.core.mnc.resolver.mncrange.McnRangeDbUtil.java

/**
 * Gets the mcc number ranges./*from   w w w .java  2 s.  co m*/
 *
 * @param mcc the mcc
 * @return the mcc number ranges
 * @throws MobileNtException the mobile nt exception
 */
public static List<NumberRange> getMccNumberRanges(String mcc) throws MobileNtException {
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    String sql = "SELECT mnccode,brand,rangefrom,rangeto " + "FROM mcc_number_ranges " + "WHERE mcccode = ?";

    List<NumberRange> lstranges = new ArrayList();

    try {
        conn = DbUtils.getDbConnection(DataSourceNames.WSO2TELCO_DEP_DB);
        ps = conn.prepareStatement(sql);
        ps.setString(1, mcc);
        rs = ps.executeQuery();
        while (rs.next()) {
            lstranges.add(new NumberRange(rs.getLong("rangefrom"), rs.getLong("rangeto"),
                    rs.getString("mnccode"), rs.getString("brand")));
        }
    } catch (Exception e) {
        handleException("Error occured while getting Number ranges for mcc: " + mcc + " from the database", e);
    } finally {
        DbUtils.closeAllConnections(ps, conn, rs);
    }
    return lstranges;
}

From source file:luceneindexdemo.LuceneIndexDemo.java

public static void missOperation(String type)
        throws FileNotFoundException, IOException, org.json.simple.parser.ParseException, SQLException {
    //JSONObject jsObject=new JSONObject();
    System.out.println("this brings out all your connection with the person you miss");
    String query = "match (n:People)-[r:KNOWS]-(b:People) where n.name='" + user + "' and r.relType='" + type
            + "' return filter(x in n.interest where x in b.interest) as common,b.name";
    Connection con = DriverManager.getConnection("jdbc:neo4j://localhost:7474/");
    ResultSet rs = con.createStatement().executeQuery(query);
    JSONParser jsParser = new JSONParser();
    FileReader freReader = new FileReader("/home/rishav12/NetBeansProjects/LuceneIndexDemo/location.json");
    JSONObject jsono = (JSONObject) jsParser.parse(freReader);
    JSONArray jslocArray = (JSONArray) jsono.get("CHENNAI");
    int count = 0;
    while (rs.next()) {
        System.out.println(rs.getString("b.name"));
        String searchQuery = "start n=node:restaurant('withinDistance:[" + jslocArray.get(0) + ","
                + jslocArray.get(1) + ",13.5]') where ";
        JSONArray jsArray = (JSONArray) jsParser.parse(rs.getString("common"));
        Iterator<JSONArray> iterJsArray = jsArray.iterator();

        count++;/*from  w w  w  .j  a  v  a  2  s.  com*/
        int k = 0;
        int flag = 0;
        while (iterJsArray.hasNext()) {
            flag = 1;
            if (k == 0) {
                searchQuery = searchQuery + "n.type='" + iterJsArray.next() + "'";
                k = k + 1;

            } else
                searchQuery = searchQuery + " or n.type='" + iterJsArray.next() + "'";
        }

        if (flag == 1) {
            searchQuery += " return n.name,n.type";
            ResultSet commonInterest = con.createStatement().executeQuery(searchQuery);
            System.out.println("Sir based on your common interests with " + rs.getString("b.name")
                    + " \ni will plan out something nearby you");
            while (commonInterest.next()) {
                System.out
                        .println(commonInterest.getString("n.name") + " " + commonInterest.getString("n.type"));
            }
        } else {
            System.err.println("you do not seem to share any common interest with" + rs.getString("b.name"));
        }

    }
    return;

}

From source file:controler.DbModules.java

public static String findName(String EmailAddress) {
    String usql = "SELECT name FROM customer WHERE email_adress=\"" + EmailAddress + "\"";
    Connection conn = DbModules.getConnection();
    String name = null;//  ww w.j  a  v  a2 s.c o m
    try {
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(usql);
        if (rs.next()) {
            name = rs.getString("name");
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return name;
}

From source file:com.datatorrent.contrib.hive.HiveMockTest.java

public static void hiveInitializeMapDatabase(HiveStore hiveStore) throws SQLException {
    hiveStore.connect();/*  w  ww .j ava2s. com*/
    Statement stmt = hiveStore.getConnection().createStatement();
    // show tables
    String sql = "show tables";

    LOG.debug(sql);
    ResultSet res = stmt.executeQuery(sql);
    if (res.next()) {
        LOG.debug(res.getString(1));
    }

    stmt.execute("DROP TABLE " + tablemap);

    stmt.execute("CREATE TABLE IF NOT EXISTS " + tablemap
            + " (col1 map<string,int>) PARTITIONED BY(dt STRING) ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t'  \n"
            + "MAP KEYS TERMINATED BY '" + delimiterMap + "' \n" + "STORED AS TEXTFILE ");
    hiveStore.disconnect();
}

From source file:net.tirasa.ilgrosso.resetdb.Main.java

private static void resetPostgreSQL(final Connection conn) throws Exception {

    final Statement statement = conn.createStatement();

    final ResultSet resultSet = statement
            .executeQuery("SELECT 'DROP TABLE ' || c.relname || ' CASCADE;' FROM pg_catalog.pg_class c "
                    + "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "
                    + "WHERE c.relkind IN ('r','') AND n.nspname NOT IN ('pg_catalog', 'pg_toast') "
                    + "AND pg_catalog.pg_table_is_visible(c.oid)");
    final List<String> drops = new ArrayList<String>();
    while (resultSet.next()) {
        drops.add(resultSet.getString(1));
    }//from w ww . ja  v  a2  s.  c o  m
    resultSet.close();

    for (String drop : drops) {
        statement.executeUpdate(drop.substring(0, drop.length() - 1));
    }

    statement.close();
    conn.close();
}

From source file:com.microsoft.sqlserver.jdbc.connection.PoolingTest.java

/**
 * setup connection, get connection from pool, and test threads
 * /* w ww.j  a v  a  2 s .  c  o m*/
 * @param ds
 * @throws SQLException
 */
private static void connect(DataSource ds) throws SQLException {
    Connection con = null;
    PreparedStatement pst = null;
    ResultSet rs = null;

    try {
        con = ds.getConnection();
        pst = con.prepareStatement("SELECT SUSER_SNAME()");
        pst.setQueryTimeout(5);
        rs = pst.executeQuery();

        // TODO : we are commenting this out due to AppVeyor failures. Will investigate later.
        // assertTrue(countTimeoutThreads() >= 1, "Timeout timer is missing.");

        while (rs.next()) {
            rs.getString(1);
        }
    } finally {
        if (rs != null) {
            rs.close();
        }

        if (pst != null) {
            pst.close();
        }

        if (con != null) {
            con.close();
        }
    }
}

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

public static List<String> getPublicKeysForSystem(Connection con, Long systemId) {
    List<String> publicKeyList = new ArrayList<String>();

    if (systemId == null) {
        systemId = -99L;/*from  ww w .  j  a  v  a2  s. c o m*/
    }
    try {
        PreparedStatement stmt = con.prepareStatement(
                "select * from public_keys where (profile_id is null or profile_id in (select profile_id from system_map where system_id=?)) and enabled=true");
        stmt.setLong(1, systemId);
        ResultSet rs = stmt.executeQuery();
        while (rs.next()) {
            publicKeyList.add(rs.getString("public_key"));
        }
        DBUtils.closeStmt(stmt);

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

    return publicKeyList;

}

From source file:com.paladin.sys.db.QueryHelper.java

/**
 * ?/*from  w w  w .j av a 2s.  c  o  m*/
 *
 * @param rs 
 * @return Map<String, String>  Map
 * @throws SQLException
 */
private static Map<String, Object> getMapFromRs(final ResultSet rs) {
    Map<String, Object> t_map = new HashMap<String, Object>();
    int columnCount = 0;
    try {
        columnCount = rs.getMetaData().getColumnCount();// ?
        // ????
        for (int i = 0; i < columnCount; i++) {
            t_map.put(rs.getMetaData().getColumnName(i + 1).toUpperCase(),
                    Tools.null2String(rs.getString(i + 1)));// ??map
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return t_map;
}