You returned ResultSet
reference rs
after closing the connection.
ResultSet
uses 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();
}
}