从结果集 Java 中获取值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34325209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 15:32:18  来源:igfitidea点击:

Get value from ResultSet Java

javasqljdbcresultset

提问by Bui Quang Huy

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

我想在查询数据库后从 ResultSet 获取值,所以我该怎么做。这是我的一些代码行

    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:

它打印:“1”,不是我想要的值。任何人都可以帮我解决这个问题。这是用户表的示例数据:

Example data

示例数据

采纳答案by java acm

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

你没有提供更多关于你的问题的细节,但这是一个例子:
你有一个带有这些字段的人员类,你可以自己制作 Setter Getter

class Person{
    String name;
    int id;
}

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

然后在你的 ResultSet 中:
认为你的表有两列(“userid”和“firstname”),第一列是“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

如果您的结果不止一个,您必须将 Person 更改为 Person[] 或“ArrayList”对象