我想将数据插入数组,以便可以访问特定值并显示它们。我是Java的新手,我希望答案很简单。
try {
Statement stmt = conn.createStatement();
String sql = "SELECT * FROM " + tableName;
ResultSet results = stmt.executeQuery(sql);
ResultSetMetaData rsmt = results.getMetaData();
int numberOfColumns = rsmt.getColumnCount();
for (int i = 1; i <= numberOfColumns; i++) {
System.out.print(rsmt.getColumnLabel(i) + "\t\t\t");
}
System.out.println("\n-------------------------------------------------------------------------------");
while (results.next()) {
int s_no = results.getInt(1);
String s_name = results.getString(2);
String s_surname = results.getString(3);
System.out.println(s_no + "\t\t\t" + s_name + "\t\t\t" + s_surname);
}
results.close();
stmt.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Records were not returned", "Error", JOptionPane.ERROR_MESSAGE);
System.out.println(e.getMessage());
}
无法将结果集数据存储在数组中。
更好地创建pojo类学生
public class Student {
private int s_no;
private String s_name;
private String s_surname;
public int getS_no() {
return s_no;
}
public void setS_no(int s_no) {
this.s_no = s_no;
}
public String getS_name() {
return s_name;
}
public void setS_name(String s_name) {
this.s_name = s_name;
}
public String getS_surname() {
return s_surname;
}
public void setS_surname(String s_surname) {
this.s_surname = s_surname;
}
}
存储逻辑:-
ResultSet results = stmt.executeQuery(sql);
List<Student> studs = new ArrayList<Student>();
while (results.next()){
Student stud = new Student();
stud.setS_no(results.getInt(1));
stud.setS_name(results.getString(2));
stud.setS_surname(results.getString(3));
studs.add(stud);
}
所有学生都已添加到列表中。请循环访问此列表以获取学生数据。
希望这对您有用