Jill Jill - 5 months ago 18
Java Question

Why is the returned ResultSet null

Given this Table Structure:

enter image description here

I want to get basic details of a user from a database, so
I created a

ResulSet
named
rst
(see code below).
When I iterate over
rst
it always returns
null
.

public ResultSet Detail(String mobile) throws Exception {
dbConnect(); // make connection
String sql = "select * from profile where mobile = ?";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, mobile);
ResultSet rst = pstmt.executeQuery();
dbClose(); // connection closed
return rst;
}


Now if I iterate over
rst
after having received it from return, I get the
null
value.

try {
ResultSet rst = new DB().Detail(mobile);
String fname = rst.getString("firstname");
String lname = rst.getString("lasttname");
String date = rst.getString("dateofbirth");
System.out.println("First name : " + fname + "\nLast Name : " + lname + "\nDate of Birth : " + date);
} catch (Exception exc) {
exc.printStackTrace();
}


Output:

First name : null
Last name : null
Date of Birth : null

Answer

it is very bad practice to iterate ResultSet as in your code.

Concept:(General Solution)

1. Always iterate your ResultSet before connection is closed, otherwise it will give you NULL as you are getting and if at the same time many connections to the database is requested, it will cause Unavilibility Of Sockets as socket write exception.

2. always before iterating ResultSet, initialize it by rst.next() this returns Boolean, not mandatory to catch it. Otherwise this will give you Exception : Before Start Of ResultSet.

Your Problems Solution:

try {
   ResultSet rst = new DB().Detail(mobile);
   rst.next();  // only add this line
   String fname = rst.getString("firstname");
   String lname = rst.getString("lasttname");
   String date = rst.getString("dateofbirth");
   System.out.println("First name : " + fname + "\nLast Name : " +lname+"\nDate of Birth : " + date);
} 
catch (Exception exc) {
  exc.printStackTrace();
}
Comments