Bui*_*Huy 3 java sql jdbc resultset
我想在查询到数据库后从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));
}
Run Code Online (Sandbox Code Playgroud)
它打印:“ 1”,而不是我想要的值。谁能帮我这个忙。这是usertable的示例数据:
您没有提供有关问题的更多详细信息,但这是一个示例:
您有一个包含此字段的人员类,您可以自己创建“塞特·盖特”
class Person{
String name;
int id;
}
Run Code Online (Sandbox Code Playgroud)
然后在您的ResultSet中:
认为您的表有两列(“ userid”和“ firstname”),第一列是“ userid”
PreparedStatement ps = null;
Connection con = null;
String SQL = "SELECT * from usertable LIMIT 1";// LIMIT 1 because you have one Person Object to fill otherwise you must be have an Array of Person
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果结果不止一个,则必须将Person更改为Person []或“ ArrayList”对象
| 归档时间: |
|
| 查看次数: |
42048 次 |
| 最近记录: |