Database
  Home arrow Database arrow Page 4 - Using the SQLCommand Object
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
ASP Web Hosting  
ASP.NET Web Hosting 
Mobile Linux 
App Generation ROI 
Windows Web Hosting
 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
DATABASE

Using the SQLCommand Object
By: McGraw-Hill/Osborne
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 2 stars2 stars2 stars2 stars2 stars / 12
    2005-06-02

    Table of Contents:
  • Using the SQLCommand Object
  • Adding the System.Data.SqlClient Namespace
  • Executing Parameterized SQL Statements
  • Executing Stored Procedures with Return Values
  • Executing Transactions

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Using the SQLCommand Object - Executing Stored Procedures with Return Values


    (Page 4 of 5 )

    Stored procedures are the core of most database applications—and for good reason. In addition to their performance benefits, stored procedures can also be a mechanism for restricting data access to the predefined interfaces that are exposed by the stored procedures. Similar to prepared SQL statements, stored procedures get significant performance benefits from the fact that they are compiled before they are used. This allows the database to forego the typical parsing steps that are required, skipping the need to create an access plan. Stored procedures are the true workhorse of most database applications, and they are almost always used for database insert, update, and delete operations, as well as for retrieving single values and result sets. In the following examples, you see how to execute SQL Server stored procedures using the SqlCommand object. In the first example that follows, you’ll see how to execute a stored procedure that accepts a single input parameter and returns a scalar value.

    The following listing presents the T-SQL source code required to create the StockValue stored procedure that will be added to the sample Northwind database. You can create this stored procedure by executing this code using Query Analyzer.

      CREATE PROCEDURE StockValue
          @ProductID int
      AS
      DECLARE @StockValue money
      SELECT StockValue = (UnitsInStock * UnitPrice)
      FROM Products WHERE ProductID = @ProductID
      RETURN @StockValue

    In the preceding listing, you can see that the StockValue stored procedure accepts a single input parameter. That parameter is an Integer value that’s used to identify the ProductID. The StockValue stored procedure returns the stock value of that ProductID from the Products table in the Northwind database. The stock value is calculated by retrieving the UnitsInStock number and multiplying it by the value in the UnitPrice column. The results are then assigned to the @StockValue variable, which is returned as a scalar value by the stored procedure. After the sample stored procedure has been created in the Northwind database, it can be called by your ADO.NET applications. The following example shows how to use the SQLCommand class form VB.NET to execute the StockValue stored procedure and retrieve the scalar value that it returns:

    Private Sub SQLCommandSPScalar(ByVal sServer As String, _
          ByVal sDB As String)
      Dim cn As New SqlConnection("SERVER=" & sServer _
         
    & ";INTEGRATED SECURITY=True;DATABASE=" & sDB)
      ' Create the command object and set the SQL statement
      Dim cmd As New SqlCommand("StockValue", cn) 
      cmd.CommandType = CommandType.StoredProcedure
      'Create the parameter
      cmd.Parameters.Add("@ProductID", SqlDbType.Int) 
      cmd.Parameters("@ProductID").Direction = _
         
    ParameterDirection.Input
      cmd.Parameters("@ProductID").Value = 1
      Try
         
    Dim nStockValue As Decimal
          ' Open the connection and execute the command
          cn.Open()
          nStockValue = cmd.ExecuteScalar()
          txtMid.Text = nStockValue
     
    Catch e As Exception
         
    MsgBox(e.Message)
      End Try
      ' Close the connection
      cn.Close()
    End Sub

    Following is the C# version of the SQLCommandSPScalar subroutine that calls a SQL stored procedure and returns a scalar value:

    private void SQLCommandPSScalar(string sServer, string sDB)
    {
        SqlConnection cn = new SqlConnection("SERVER=" + sServer
            + ";INTEGRATED SECURITY=True;DATABASE=" + sDB);
        // Create the command object and set the SQL statement  
        SqlCommand cmd = new SqlCommand("StockValue",  cn); 
        cmd.CommandType = CommandType.StoredProcedure;
        // Create the parameter
        cmd.Parameters.Add("@ProductID",  SqlDbType.Int); 
        cmd.Parameters["@ProductID"].Direction =
              ParameterDirection.Input;
        cmd.Parameters["@ProductID"].Value = 1;
        try
        {
              decimal nStockValue;
              // Open the connection and execute the command
              cn.Open();
              nStockValue = (decimal)cmd.ExecuteScalar();
              txtMid.Text = nStockValue.ToString();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        // Close the connection
        cn.Close();
    }

    In the beginning of this routine you can see where the cn SqlConnection object is created, followed by the creation of the SqlCommand object named cmd. In this example, the constructor for the SqlCommand object uses two parameters. The first parameter is a string that accepts the command that will be executed. This can be either a SQL statement or the name of the stored procedure. In this example, you can see that the name of the StockValue stored procedure is used. The second parameter is used for the name of the SqlConnection object that will be used to connect to the target database. After the cmd SqlCommand object has been created, its CommandType property is set to CommandType.StoredProcedure indicating that a stored procedure will be executed. The CommandType property can accept any of the values shown in the following table:

    CommandType ValuesDescription
    CommandType.StoredProcedureThe command is a stored procedure.
    CommandType.TableDirectThe command is the name of a database table.
    CommandType.TextThe command is a SQL statement.

    After the SqlCommand object’s CommandType property is set to CommandType.StoredProcedure, the SqlParameter object used to supply the input value to the StockValue stored procedure is created. SqlParameter objects can be created either by using the SqlParameter class constructor or by executing the SqlCommand object’s Parameters collection Add method. In this example, the parameter is created using the Add method of the SqlCommand object’s Parameters collection. The first parameter supplied to the Add method is a string containing the name of the parameter. In this case "@ProductID". Again, note that replaceable parameters used by the SQLParameter object must begin with the at symbol (@). The second parameter uses the SqlDbType.Int enumeration to indicate that the parameter will contain an Integer value. The next line sets the Direction property to the value ParameterDirection.Input to indicate that this is an input parameter. Last, the SqlParameter object’s Value property is set to 1—storing a value of 1 to pass to the StockValue stored procedure.

    The next section of code sets up a Try-Catch block to open the connection to the SQL Server system and then executes the StockValue stored procedure. The important point to note in the Try-Catch block is that the cmd SqlCommand object’s ExecuteScalar method is used to execute the StockValue stored procedure and the return value is assigned to the nStockValue variable. The contents of the nStockValue variable are then assigned to a text box. Like the earlier examples, if the connection or the stored procedure fails, a message box showing the error text will be displayed to the end user. Then the connection will be closed.

    More Database Articles
    More By McGraw-Hill/Osborne


     

    Buy this book now. This article is taken from chapter 8 of ADO.NET: The Complete Reference, written by Michael Otey and Denielle Otey (McGraw-Hill/Osborne, 2004; ISBN: 0072228989). Check it out at your favorite bookstore. Buy this book now.

    DATABASE ARTICLES

    - Excel Reference
    - Database Programming in C# with MySQL : Usin...
    - Formatting Techniques for Data Access from E...
    - Data Access from Excel VBA
    - Generating a Multiple Table Crystal Report u...
    - ADO and the Command Object
    - On Wiring Up an ADO Data Control
    - Reading and Writing to Files on the Intranet
    - Using ADO Record to Create and Navigate Intr...
    - Using Data Access Pages to Access Data on a ...
    - Using ADO with the SQL Native Client
    - ADO`s Stream Object
    - Opening a Record Object Referencing an Open ...
    - Introducing Jasper (SQL Anywhere 10 Beta)
    - Creating a Database Project in VS 2005

     
    Application Delivery: Everything You Wanted to Know, but Didn`t Know You Needed to Ask
    A comprehensive guide to examining the topics of Wide-area Data Services and app....

     
    Best Practices: Safe and Secure Hardware Asset Recovery
    Companies increasingly must meet EPA and local requirements for the disposal of ....

     
    Managing SSL Security in Multi-Server Environments
    Read this white paper to learn how to simplify management of your organization's....

     
    Open Source Security Myths
    Open Source Software (OSS) is computer software whose source code is available t....

     
    Power and Cooling Capacity Management for Data Centers
    This paper describes the principles for achieving power and cooling capacity man....

     




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 5 hosted by Hostway
    Stay green...Green IT