我是编程新手。我正在尝试制作一个软件。但我有问题。
问题是: 我的软件是学校管理。因此,当我在java中输入学生卷号时,我需要检索我存储在mysql中的信息(名称,年龄等)。但是我输入的代码总是为我输入的任何滚动提供相同的信息。请帮忙
String LibraryCardNo = txtCard.getText();
String firstName = "";
String lastName = "";
String Job = "";
String Age = "";
String LibraryCard = "";
try{
Class.forName("java.sql.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3307/library?" + "user=root&password=ainkhalid");
Statement s = con.createStatement();
String query = "select * from application";
ResultSet rs = s.executeQuery(query);
while(rs.next()){
firstName = rs.getString("firstName");
lastName = rs.getString("lastName");
Job = rs.getString("job");
Age = rs.getString("age");
LibraryCard = rs.getString("LibraryCardNo");
}
rs.close();
s.close();
con.close();
}
catch(Exception e){
String msg = e.getMessage();
System.out.println("The problem is :"+msg);
}
txtLast.setText(lastName);
txtFirst.setText(firstName);
txtJob.setText(Job);
txtAge.setText(Age);
答案 0 :(得分:1)
那是因为你循环结果,但只保留对最后一个的引用
while(rs.next()){
firstName = rs.getString("firstName");
lastName = rs.getString("lastName");
Job = rs.getString("job");
Age = rs.getString("age");
LibraryCard = rs.getString("LibraryCardNo");
}
方法ResultSet#next()
返回true
并移动其内部迭代器,只要还有要读取的数据。
立即尝试打印它们或将所有数据封装到一个类中,实例化对象并将它们添加到列表中,然后打印出来。
public class Student {
String firstName = "";
String lastName = "";
String job = "";
String age = "";
String libraryCard = "";
// getters, setters, and constructors
}
然后
List<Student> students = new LinkedList<>();
while(rs.next()){
firstName = rs.getString("firstName");
lastName = rs.getString("lastName");
Job = rs.getString("job");
Age = rs.getString("age");
LibraryCard = rs.getString("LibraryCardNo");
Student student = new Student(firstName, lastName, Job, Age, LibraryCard);
students.add(student);
}
// display them accordingly
显然,如果您只想从数据库中检索一行,则必须切换查询。像
这样的东西 String query = "select * from application where roll = ?";
使用PreparedStatement
并设置?
占位符的值。