简体   繁体   中英

How to get one student from an SQL server DB using Java?

I've been trying to get this code to work for several hours now and need some help. I have a database that contains a table called "Students". I'm trying to write the below method that selects one student based on user's input (which shall happen later in a gui). For now I am simply testing it in a Test class.

I want to get all the values of student in a system.out.print . What am I doing wrong?

public Student getOneSpecificStudent(int studentID) throws SQLException {

        Connection con = null;
        PreparedStatement stm = null;

        try {
            con = DatabaseConnection.getConnection();
            stm = con.prepareStatement("SELECT * FROM Student WHERE studentID = ?");
            stm.setInt(1, studentID);

            ResultSet rs = stm.executeQuery();

            Student student = new Student();
            while (rs.next()) {
                return (new Student(studentID = rs.getInt("studentID"), rs.getString("studentSSN"), rs.getString("studentName"), rs.getString("studentAddress"), rs.getString("studentPhoneNumber")));

            }
            return student;
        } finally {
            DbUtils.close(con);
            DbUtils.close(stm);
        }
    }

My current problem is that this testmethod:

    try {
        dal.getOneSpecificStudent(2);
        System.out.println("Student is: " + student.getStudentSSN() + 
student.getStudentID() );
    } catch (SQLException e) {
        System.out.println("SQL exception" + e );
    }

Returns null.

There is some rather "odd" code here:

    dal.getOneSpecificStudent(2);
    System.out.println("Student is: " + student.getStudentSSN() + 
                       student.getStudentID());

You are trying to call methods on a student variable ... but that's not related in any way to the previous statement.

  1. The getOneSpecificStudent(2) call returns a value, but you are discarding it.
  2. The student variable in the body of the getOneSpecificStudent method is a local variable. It is not the same variable that you are printing.

So maybe your assertion that something "Returns null" should be reconsidered .....

You should do this like:

 Student student = dal.getOneSpecificStudent(2); System.out.println("Student is: " + student.getStudentSSN() + student.getStudentID() ); 

So it will print the values.

So are you getting null values or you getting NullPointerException . If you are getting null values its because you are initialising your Student Object as empty in Student student = new Student(); Since you haven't passed anything in the constructor. The student object is empty means getters will return null values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM