< Previous | Next >

Completed selectItems.egl file after lesson 4A

This code is the completed version of the selectItems.egl file after lesson 4A. If you see any errors marked by red X symbols in the file, make sure your code matches this code:
package programs;

import eglderbyr7.data.Item;
import eglderbyr7.primitivetypes.data.Price;

program selectItems type BasicProgram {}
  
  function main()
    minPrice, maxPrice Price?;
    minPrice = 50;
    maxPrice = 500;
    try
      printItemRange(minPrice, maxPrice);
    onException(exception SQLException)
      handleDBException(exception);
    end
  end
  
  function printItemRange(minPrice Price? in, maxPrice Price? in)
    
    selectStatement STRING = "select * from EGL.ITEM where ";
    
    if (minPrice == NULL && maxPrice == NULL)
      // Two empty parameters;
      // return all rows with PRICE greater than zero.
      selectStatement ::= "EGL.ITEM.PRICE > 0 ";
    else
    
      if (minPrice != NULL && maxPrice != NULL)
        // Both parameters were specified.
        selectStatement ::= "EGL.ITEM.PRICE between ":: minPrice :: " and " :: maxPrice :: " ";
      else
        // Only one parameter was specified.
        if (minPrice == NULL)
          // Maximum was specified.
          selectStatement ::= "EGL.ITEM.PRICE <= " :: maxPrice :: " ";
        else
          // Minimum was specified.
          selectStatement ::= "EGL.ITEM.PRICE >= ":: minPrice :: " ";
        end
      end
      
    end
    
    // Regardless of parameters, sort by price.
    selectStatement ::= "order by EGL.ITEM.PRICE";
    
    // Print completed SQL code.
    SysLib.writeStdout("Completed query: "::selectStatement);
    
    // Prepare the statement to be used.
    tempItem Item;
    prepare preparedStatement 
      from selectStatement
      for tempItem;
    
    // Use the prepared statement in place of explicit SQL.
    open expensiveItems for tempItem with preparedStatement;
    
    // Print the results to the console.
    forEach (tempItem)
      SysLib.writeStdout(tempItem.Name :: " " ::
        tempItem.Description :: " $" :: tempItem.Price);
    end
    
  end
  
  function printExpensiveItems(maxPrice Price in)
    
  tempItem Item;
  open expensiveItems for tempItem with
    #sql{
      select
        EGL.ITEM.ITEM_ID, EGL.ITEM.NAME, EGL.ITEM.IMAGE, 
        EGL.ITEM.PRICE, EGL.ITEM.DESCRIPTION
      from EGL.ITEM
      where
        EGL.ITEM.PRICE >= :maxPrice
      order by
        EGL.ITEM.ITEM_ID asc
    };
    
  forEach (tempItem)
    SysLib.writeStdout(tempItem.Name :: " " ::
      tempItem.Description :: " $" :: tempItem.Price);
  end
    
  end
  
  function handleDBException(exception SQLException)
    SysLib.writeStdout("Error accessing database. "::
      "See Troubleshooting section");
    SysLib.writeStdout(exception.message);
  end
  
end

Return to Lesson 4A: Using a prepared statement.

< Previous | Next >

Feedback