我是编程新手。我正在试着做一个软件。但我有个问题。
问题是:我的软件是学校管理软件。因此,当我在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);发布于 2013-09-28 03:17:07
这是因为您循环遍历结果,但只保留对最后一个结果的引用
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考虑阅读this official tutorial。
显然,如果您只想从数据库中检索一行,则必须切换查询。就像这样
String query = "select * from application where roll = ?";使用PreparedStatement并设置?占位符的值。
https://stackoverflow.com/questions/19058442
复制相似问题