Reputation: 1837
I have a method that takes a string value as a parameter and then checks if that string value exists in the database! The method should return true if the string value already exist and false otherwise! Before i run the method i get a compilation error " missing return statement"! Does anyone spot an error in the code below ?
public boolean checkID(String sid)
{
try
{
String sessionID = null;
if(dBConnection.connect())
{
Connection con = dBConnection.getConnection();
String query = "SELECT sidvalue FROM sessionid where tokenvalue='" + sid + "'";
Statement pstmt = con.createStatement();
ResultSet resultset = pstmt.executeQuery(query);
while (resultset.next())
{
sessionID = resultset.getString(1);
if(sid.equalsIgnoreCase(sessionID))
{
return true;
}
else
{
return false;
}
}
dBConnection.disconnect();
}//End of If statement
}//End of Try block
catch (Exception e)
{
System.out.println(e);
return false;
}
}//End of method
Upvotes: 1
Views: 2214
Reputation: 25950
What if the execution doesn't pass to the if statement and/or while loop? There is no return value for such cases. Use a boolean variable or false
value to return. Just add a return false;
statement after this line dBConnection.disconnect();
, i.e. after the while loop inside the if statement of your try block, it will be done.
By the way, I suggest you to use database disconnection statement in a finally
clause, not inside try block. It's probable that dBConnection.disconnect();
will not be executed if your method returns any value inside the while loop. Move this line dBConnection.disconnect();
to a finally block just after the catch block like this:
try
{
...
}
catch(Exception e)
{
...
}
finally
{
dBConnection.disconnect();
}
Upvotes: 6
Reputation: 8012
Try the below code. It should resolve your issue:
public boolean checkID(String sid) {
try {
String sessionID = null;
if(dBConnection.connect()) {
Connection con = dBConnection.getConnection();
String query = "SELECT sidvalue FROM sessionid where tokenvalue='" + sid + "'";
Statement pstmt = con.createStatement();
ResultSet resultset = pstmt.executeQuery(query);
while (resultset.next()) {
sessionID = resultset.getString(1);
if(sid.equalsIgnoreCase(sessionID)) {
return true;
} else {
return false;
}
}
} else {
return false;
}
} catch (Exception e) {
System.out.println(e);
return false;
}
finally {
dBConnection.disconnect();
}
}//End of method
Upvotes: 0
Reputation: 923
If the if statement, if(dBConnection.connect()), returns false then there is no return statement for the method. You can either add a finally statement or you can just attach an else to the if returning the value you want
Upvotes: 1