Tri Nguyen Tri Nguyen - 20 days ago 5
Java Question

Java - NULL ResultSet

I have a function to fetch data from MySQL table

public ResultSet getAddressID(String city) throws SQLException{
String q = "SELECT PK_ADDRESS_ID FROM tbl_addresses WHERE city =" + "\""+ city+ "\";";
ResultSet rs = executeSearch(q);
return rs;
}


When I try
System.out.println(n.getAddressID("Sheffield"));
it returns
null
. Why this happened even though there are data in my table (see picture).

enter image description here

public ResultSet executeSearch(String q){
openConnection();
try{
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(q);
closeConnection();
return resultSet;
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e.getMessage());
}
finally {
closeConnection();
return null;
}
}

Answer

The problem appears to be in your executeSearch method; the finally block will always execute, so by returning null in the finally block, you essentially override what you returned in the try block!

This could be an alternative solution; note that I'm returning at the end of the method instead of within any parts of the try-catch-finally block.

public ResultSet executeSearch(String q)
{
    ResultSet toReturn = null;
    openConnection();
    try {
        Statement statement = connection.createStatement();
        toReturn = statement.executeQuery(q);
    }
    catch (Exception e) {
        JOptionPane.showMessageDialog(null, e.getMessage());
    }
    finally {
        closeConnection();
    }

    return toReturn;
}