0

我是编程新手。我正在尝试制作一个软件。但我有问题。

问题是:我的软件是校务管理。因此,当我在 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);
4

1 回答 1

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和设置?占位符的值。

于 2013-09-27T19:17:06.607 回答