从ResultSet Java中获取值



我想在查询数据库后从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));
}

上面印着:";1〃;,而不是我想要的价值。有人能帮我吗。这是usertable的示例数据:

示例数据

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

class Person{
    String name;
    int id;
}

然后在您的ResultSet中:
认为您的表有两列("userid"one_answers"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);
            }
        }
    }

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

相关内容

  • 没有找到相关文章

最新更新