Java 从数据库中填充几个jtextfield

Java 从数据库中填充几个jtextfield,java,jdbc,jtextfield,Java,Jdbc,Jtextfield,我想用从数据库检索的数据填充几个jtextfield。 我知道,我可以这样做: while (rs.next()) { tfName.setText(rs.getString("name")); tfAge.setText(rs.getString("age")); } while (rs.next()) { for (String key: KEY_STRINGS) { fieldMap.get(key).setText(rs.getString(key)); }

我想用从数据库检索的数据填充几个jtextfield。 我知道,我可以这样做:

while (rs.next()) {
   tfName.setText(rs.getString("name"));
   tfAge.setText(rs.getString("age"));
}
while (rs.next()) {
  for (String key: KEY_STRINGS) {
    fieldMap.get(key).setText(rs.getString(key));
  }
}

但是,在select方法的末尾只有一个
return
是否有更聪明的方法呢?

您可以将JTextFields放入
映射
中,然后使用数据库列键字符串作为文本字段映射的键(比如称为fieldMap),并且还可以拥有这些键字符串的数组。然后你可以做一些类似的事情:

while (rs.next()) {
   tfName.setText(rs.getString("name"));
   tfAge.setText(rs.getString("age"));
}
while (rs.next()) {
  for (String key: KEY_STRINGS) {
    fieldMap.get(key).setText(rs.getString(key));
  }
}

说到这里,
while(rs.next())
让我有点烦,因为我担心while会很快在数据库行中循环,只会真正显示数据库的最后一行。这需要更改。

您指的是哪种选择方法?还要注意,使用这样一个
while
循环来更新
JTextField
实例没有多大意义,因为每个
JTextField
只能包含一个
字符串作为文本。您不妨直接使用
ResultSet
的最后一个条目这只是一个示例,在我的情况下,我只会收到一个结果。我指的是数据库类中的通用选择方法。