我想显示从表中获取的所有信息...... 我这样做了:
String sql = "Select * from student";
ResultSet rs = stat.executeQuery(sql);
while(rs.next())
{
int id = rs.getint("idstudent");
String name = rs.getString("studentName");
}
request.setAttribute("Result", rs);
RequestDispatcher view = request.getRequestDispatcher("DBResult.jsp");
view.forward(request, response);
我必须将ResultSet更改为List才能使用它,但我无法在表中显示它们! 我怎么能这样做?
答案 0 :(得分:0)
根本不要通过ResultSet
。传递值列表。
创建一些POJO,例如Student
,其中包含两个字段:idstudent
和studentName
:
public class Student {
private int idStudent;
private String studentName;
//Getters and setters
}
然后创建List
实例。像students
:
List<Student> students = new ArrayList<Student>();
在while循环的每次迭代中创建一个Student
对象并将其添加到students
列表中:
while(rs.next())
{
Student student = new Student();
int id = rs.getint("idstudent");
student.setIdStudent(id);
String name = rs.getString("studentName");
student.setStudentName(name);
students.add(student);
}
最后,将该列表作为属性传递:
request.setAttribute("students", students);
答案 1 :(得分:0)
使用Java的规范方法是编写一个史诗级别的类,因此您将要添加一个Student
类。
public final class Student {
public final int id;
public final String name;
public Student(int id, String name) {
this.id = id;
this.name = Objects.requireNonNull(name);
}
}
然后使用ResultSet
生成List
Student
个。 ResultSet
上没有任何类型的map
运算符,所以如果不使用一个很好的库来包装JDBC,你必须求助于一个可变的List
和一个程序循环来附加到它
String sql = "Select * from student";
ResultSet rs = stat.executeQuery(sql);
List<Student> students = new ArrayList<>();
while (rs.next()) {
int id = rs.getint("idstudent");
String name = rs.getString("studentName");
students.add(new Student(id, name));
}
request.setAttribute("students", students);
RequestDispatcher view = request.getRequestDispatcher("DBResult.jsp");
view.forward(request, response);