Well, that JDBC / SQL of yours could use some updates.
But first things first. This is what happens:
ResultSet Rset = pStatement.executeQuery(sql); //Executes the query
Rset.beforeFirst(); //Moves the cursor backwards before the first row (!)
Rset.next(); //Goes to the next row
The second line throws an Exeption as the cursor is FORWARD_ONLY. Plus: You don't need that call at all!
This should solve your immediate problem:
ResultSet Rset = pStatement.executeQuery(sql);
if(Rset.next()) {
int userID = Rset.getInt("userID");
String email = Rset.getString("email");
User userReturn = new User (userID, email);
return userReturn;
} else {
//Deal with no user found
}
Now to the general stuff:
- it's good that you're preparing the Statement. But as Bashir already pointed out: If you go and use executeQuery(sql), which is a member of class Statement, you throw away the precompiled statement.
- when using PreparedStatement - use bind parameters as well. This makes your code less oen for SQL injection and
- use try-with-resource to make sure you close everything properly. Hunting down connection leaks or opened cursors is a hassle easily avoided.
In the end you'll probably end up with something like this:
public static User getUser (User user) throws Exception {
String sql = "SELECT * FROM login WHERE userID = ?;
try(PreparedStatement pStatement = conn.prepareStatement(sql)) {
pStatement.setInt(1, user.getuserID());
try(ResultSet Rset = pStatement.executeQuery()) {
if(Rset.next()) {
int userID = Rset.getInt("userID");
String email = Rset.getString("email");
User userReturn = new User (userID, email);
return userReturn;
}
}
} catch(SQLException e) {
//Deal with the exception
e.printStackTrace();
}
//Error or no user found
return null;
}