spacer
Yehuda Shiran October 10, 2002
Retrieving Selected Products from the IBuySpy Database
Tips: October 2002

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
HP to Microsoft: Thanks for Nothing
iPhone Remains Left Out as Android Scores Flash
The Year of Living the OpenSocial
A common interaction with an MSSQL database is to retrieve all records with a given attribute. A classic example is to retrieve all products with a given category ID. Usually, you'll use a stored procedure that expects a single parameter, the category ID. To accomplish this task, you need to follow the following recipe:

  1. Create an instance of connection to the database, a SqlConnection object.
  2. Create an instance of an SQL command, a SqlCommand object.
  3. Mark the command as a stored procedure.
  4. Create a parameter instance object.
  5. Set the parameter instance object's Value parameter.
  6. Add the parameter instance object to the SQL command object, created above.
  7. Execute the command.
  8. Return the SqlDataReader result to the caller.

Let's take an example. The ProductsDB.js file includes the method GetProducts(categoryID: int). As its name implies, this method retrieves all products belonging to categoryID. It follows the recipe above, calling the stored procedure ProductsByCategory. This stored procedure expects a single parameter, CategoryID. It returns a table of all products with the given CategoryID. Here is the code:

  public function GetProducts(categoryID: int) : SqlDataReader {
    var myConnection : SqlConnection = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
    var myCommand : SqlCommand = new SqlCommand("ProductsByCategory", myConnection);
    myCommand.CommandType = CommandType.StoredProcedure;
    var parameterCategoryID : SqlParameter = new SqlParameter("@CategoryID", SqlDbType.Int, 4);
    parameterCategoryID.Value = categoryID;
    myCommand.Parameters.Add(parameterCategoryID);
    myConnection.Open();
    var result : SqlDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
    return result;
  }

People who read this tip also read these tips:

Look for similar tips by subject:

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

webref The latest from WebReference.com Browse >
Administering RBAC in PHP 5 CMS Framework · xref: Automatic Cross Referencing Script · Book Review: Content Rich
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Gateway Launches New Core i7-powered FX-Series Gaming PCs · Review: Lenovo ThinkPad SL300 · EBay, Alternative Site Holiday Resources for Sellers