Get value from ResultSet Java

62,677

you dont put more details of your problem but this is an example :
you have a person class with this fields you could to make Setter Getter by yourself

class Person{
    String name;
    int id;
}

then in your ResultSet :
think your table have two column ("userid" and "firstname") and first column is "userid"

    PreparedStatement ps = null;
    Connection con = null;
    // LIMIT 1 because you have one Person Object to fill otherwise you must be have an Array of Person
    String SQL = "SELECT * from usertable LIMIT 1";
    try {
        con = DBConnection.getConnection();
        ps = con.prepareStatement(SQL);

        ResultSet rs = ps.executeQuery();
        Person p = null;

        while (rs.next()) {
            p = new Person();
            p.id = rs.getInt(1);
            // or p.id=rs.getInt("userid"); by name of column
            p.name = rs.getString(2);
            // or p.name=rs.getString("firstname"); by name of column
        }
        return p;
    } catch (
        SQLException ex) {
        Logger.getLogger(YourClassName.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    } finally {
        if (con != null) {
            try {
                con.close();
            } catch (SQLException ex) {
                Logger.getLogger(YourClassName.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException ex) {
                Logger.getLogger(YourClassName.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

if your Result is more than one you must be change Person to Person[] or "ArrayList" Object

Share:
62,677
Bui Quang Huy
Author by

Bui Quang Huy

A software engineer with experience in .NET ...

Updated on December 08, 2020

Comments

  • Bui Quang Huy
    Bui Quang Huy over 3 years

    I want to get value from ResultSet after query to the database so how can I do it. This is some line of my code

        conn = DBConnection.connect();
        String SQL = "SELECT * from usertable";
        // ResultSet
        ResultSet rs = conn.createStatement().executeQuery(SQL);
        if (rs.next()) {
            System.out.println(rs.getString(1));
        }
    

    It printed: "1", not the value I want to get. Could anyone help me about this. This is example data of usertable:

    Example data