-2

A table named teacher contains the name, contact and email CountTeacher function:

public ResultSet countTeacher() throws SQLException{
  try {
      con=Dbconnection.getCon();
      stmt=con.prepareStatement("select COUNT(*) from teacher");
      rs=stmt.executeQuery();
  }catch(Exception e) {
      e.getMessage();
      con.close();
  }
  return rs;
}

how do i call this funnction and display it on my jsp page using scriplets I imported the java file with this function on the page I want to display the result on and gave it an id. How do I call it now

miiiii
  • 1,580
  • 1
  • 16
  • 29
Siddharth Joshi
  • 265
  • 2
  • 10

1 Answers1

0

You returned ResultSet reference rs after closing the connection.

ResultSetuses cursor to point the rows returned by the database query. If you close connection before actually using the result, the ResultSet would be useless, as the connection is closed, it removes the cursor too.

It is worth reading this post

As a suggestion to your problem, I would recommend below approach..

Make a POJO for your table..

class Teacher{
    private String name;
    private String contact;
    private String email;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getContact() {
        return contact;
    }

    public void setContact(String contact) {
        this.contact = contact;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

And, now in your method, you should return list of teacher which can be passed to some other method calls, even when the database connection is closed.

    public List<Teacher> countTeacher() throws SQLException {
        try {
            con = Dbconnection.getCon();
            stmt = con.prepareStatement("select COUNT(*) from teacher");
            rs = stmt.executeQuery();
            Teacher teacher = new Teacher();
            List<Teacher> teachers = new ArrayList<Teacher>();
            while(rs.next()){
                String name = rs.getString("name");
                String contact = rs.getString("contact");
                String email = rs.getString("email");

                teacher.setName(name);
                teacher.setContact(contact);
                teacher.setEmail(email);

                teachers.add(teacher);
            }
            return teachers;

        } catch (Exception e) {
            e.getMessage();
        }
        finally{
            con.close();
        }
    }
miiiii
  • 1,580
  • 1
  • 16
  • 29