Search code examples
javamysqlresultset

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;
    }
}

Solution

  • 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.

    /**
     * Converts a provided ResultSet into a generic List so that the
     * ResultSet can be closed while the data persists.
     * Source: http://stackoverflow.com/a/7507225/899126
     */
    public List convertResultSetToList(ResultSet rs) throws SQLException
    {
        ResultSetMetaData md = rs.getMetaData();
        int columns = md.getColumnCount();
        List list = new ArrayList(50);
    
        while (rs.next())
        {
            HashMap row = new HashMap(columns);
            for(int i = 1; i <= columns; ++i)
            {
                row.put(md.getColumnName(i), rs.getObject(i));
            }
            list.add(row);
        }
    
        return list;
    }
    
    public List executeSearch(String q)
    {
        List toReturn;
        openConnection();
        try {
            Statement statement = connection.createStatement();
            toReturn = this.convertResultSetToList(statement.executeQuery(q));
        }
        catch (Exception e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
            toReturn = new ArrayList();
        }
        finally {
            closeConnection();
        }
    
        return toReturn;
    }