Home > Software design >  How to retrieve an object from ResultSet in java?
How to retrieve an object from ResultSet in java?

Time:02-18

So I tried to make a getRecord class to retrieves info from database based on the ID the user entered,

public Student getRecord(String id) {
        String queryStr = "SELECT * FROM "   tableName   " WHERE ID = ?";
        Student student = null;
        try {
            stmt = conn.prepareStatement(queryStr);
            stmt.setString(1, id);
            ResultSet rs = stmt.executeQuery();
            int count = 1;
            
            if (rs.next()) {
                String level = rs.getString("Level");
                char level1 = level.charAt(0);
                student = new Student(id, rs.getString("IC"), rs.getString("Name"), level1, rs.getObject("ProgrammeCode"), Integer.parseInt(rs.getString("Yr")));
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage(), "ERROR", JOptionPane.ERROR_MESSAGE);
        }
        return student;
    }

So it run the query and call the constructor of student,

public Student(String id, String ic, String name, char level, Programme programme, int year) {
        this.id = id;
        this.ic = ic;
        this.name = name;
        this.level = level;
        this.programme = programme;
        this.year = year;
    }

To create an object for student class and then return it to the main program. However, the student constructor also need another object of programme. How can i retrieve the object from the database through ResultSet? I have stucked on this for hours and attempted to use getObject but it didn't work. Please guide me. TQ and have a good day.

CodePudding user response:

SOLUTION FOUND THANKS TO @Joop Eggen

I managed to solve this by declaring and initializing a new object, replacing the rs.getString("ProgrammeCode"); to (new Programme(rs.getString("ProgrammeCode"))).

  • Related