从 ResultSet 获取值 Java
Get value from 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”,不是我想要得到的值。谁能帮我解决这个问题。这是用户表的示例数据:
您没有详细说明您的问题,但这是一个示例:
你有一个人 class 拥有这些字段你可以自己制作 Setter Getter
class Person{
String name;
int id;
}
然后在您的结果集中:
认为您的 table 有两列("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);
}
}
}
如果您的结果不止一个,您必须将 Person 更改为 Person[] 或 "ArrayList" Object
我想在查询数据库后从 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”,不是我想要得到的值。谁能帮我解决这个问题。这是用户表的示例数据:
您没有详细说明您的问题,但这是一个示例:
你有一个人 class 拥有这些字段你可以自己制作 Setter Getter
class Person{
String name;
int id;
}
然后在您的结果集中:
认为您的 table 有两列("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);
}
}
}
如果您的结果不止一个,您必须将 Person 更改为 Person[] 或 "ArrayList" Object