Database
  Home arrow Database arrow Page 2 - 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 - Adding the System.Data.SqlClient Namespace


    (Page 2 of 5 )

    Although using the visual connection components provided by the Visual Studio.NET design environment is pretty easy, in the long run, you’ll probably find it simpler to use the ADO.NET objects by just writing code. To use the SqlCommand class in your project, you first need to add an import directive for the System.Data.SqlClient Namespace in your project. The following example illustrates how to do this for a VB.NET project:

      Imports System.Data.SqlClient

    For a C# project, you need to add an import directive for the System.Data.SqlClient Namespace as follows:

      using System.Data.SqlClient;

    After the import directive has been added, you’re ready to use code-based SqlCommand objects in your projects.

    Executing Dynamic SQL Statements Using SqlCommand

    Dynamic SQL provides an extremely flexible mechanism for working with the database. Dynamic SQL allows you to execute ad hoc queries and return the results from action queries, as well as execute SQL DDL statements to create database objects. The following SQLCommandNonQuery subroutine provides an example illustrating how you can use dynamic SQL with the ADO.NET SqlCommand object to check for the existence of a table and conditionally create it if it doesn’t exist:

      Private Sub SQLCommandNonQuery(ByVal sServer As String, _   
              ByVal sDB As String)
          Dim cn As New SqlConnection("SERVER=" & sServer _
         
    & ";INTEGRATED SECURITY=True;DATABASE=" & sDB)
          Dim sSQL As
    String
          Dim cmd As New SqlCommand(sSQL, cn)
          Try
              ' Open the connection
              cn.Open()
              ' First drop the table
              sSQL = "IF EXISTS " _
                 
    & "(SELECT * FROM dbo.sysobjects WHERE id = " _
                  & "object_id(N'[Department]') " _
                  & "AND OBJECTPROPERTY(id, N'IsUserTable') = 1) " _
                  & "DROP TABLE [department]"
             
    cmd.CommandText = sSQL
              cmd.ExecuteNonQuery()
              ' Then create the table
              sSQL = "CREATE TABLE Department " _
                
    & "(DepartmentID Int NOT NULL, " _
                
    & "DepartmentName Char(25), PRIMARY KEY(DepartmentID))"
              cmd.CommandText = sSQL
              cmd.ExecuteNonQuery()
         
    Catch e As Exception
             
    MsgBox(e.Message)
          End Try
          ' Close the connection
          cn.Close()
      End Sub

    The C# version of the SQLCommandNonQuery subroutine is shown here:

      private void SQLCommandNonQuery(string sServer, string sDB)
      {
          SqlConnection cn = new SqlConnection("SERVER=" + sServer
             
    + ";INTEGRATED SECURITY=True;DATABASE=" + sDB);
          string sSQL;
          SqlCommand cmd = new SqlCommand("", cn);
          try
          {
             
    // Open the connection
              cn.Open();
              // First drop the table
              sSQL = "IF EXISTS "
                  + "(SELECT * FROM dbo.sysobjects "
                  + "WHERE id = object_id(N'[Department]') "
                 
    + "AND OBJECTPROPERTY(id, N'IsUserTable') = 1) "
                  + "DROP TABLE [department]";
              cmd.CommandText = sSQL;
              cmd.ExecuteNonQuery();
              // Then create the table
              sSQL = "CREATE TABLE Department "
                  + "(DepartmentID Int NOT NULL, "
                 
    + "DepartmentName Char(25), "
                 
    + "PRIMARY KEY(DepartmentID))"; 
              cmd.CommandText = sSQL;
              cmd.ExecuteNonQuery();
         
    }
          catch(Exception ex)
          {
             
    MessageBox.Show(ex.Message);
          }
          // Close the connection
          cn.Close();
     
    }

    In the first part of the SQLCommandNonQuery subroutine, you can see where the sServer and sDB variables are passed as parameters. The values of these two variables are used to specify the SQL Server database server and database that will be used. Next, a new SqlConnection object named cn is created. In this example, the connection string is passed in as the first parameter of the SqlConnection object’s constructor. The connection string uses Integrated Security to connect to the server and database specified using the server and database keywords. For more information about the Sql Connection object’s connection string keywords, you can refer to Chapter 4.

    After the Connection object has been created, the sSQL variable that will be used to contain the dynamic SQL statements and an instance of the SqlCommand object named cmd are instantiated. In this example, the constructor of the cmd SqlCommand object uses two parameters—the first being a string containing the SQL statement that will be executed, and the second being the SqlConnection object that will provide the connection to the target database server. Here the sSQL string is initially empty. Next, a Try-Catch structure is set up to execute the SQL commands. The first action that you can see within the Try-Catch block uses the cn SqlConnection object’s Open method to open a connection to the SQL Server database that was specified earlier in the connection string used in the SqlConnection object’s constructor. Then, the sSQL variable is assigned a SQL statement that checks for the existence of the department table. In this SQL statement, you can see that a Select statement queries the SQL Server sysobjects table to determine if a User Table named Department exists. If the Department table is found, a DROP TABLE statement will be executed to remove the table from the target database. Otherwise, if the Department table isn’t found, no further action will be taken. In order to actually execute the SQL statement, that value in the sSQL variable is then assigned to the CommandText property of the cmd object, and then the ExcuteNonQuery method of the cmd SqlCommand object is used to send the command to the SQL Server system. The ExecuteNonQuery method is used to execute a SQL statement that doesn’t return a resultset or a specific return value.

    After the first DROP TABLE SQL command has been issued, the same sequence is followed to execute a Create Table command. First, the sSQL variable is assigned a SQL CREATE TABLE statement that creates a table named Department that consists of two columns. The first column is an integer data type named DepartmentID, which is also the primary key, and the second column is a 25-character data type named DepartmentName. Then the value in the sSQL variable is copied to the cmd object’s CommandText property, and the ExecuteNonQuery method is called to execute the CREATE TABLE SQL statement. Following the successful completion of the ExecuteNonQuery method, the Department Table will exist in the database that was earlier identified in the sDB variable.

    If an error occurs during any of these operations, the SqlConnection object’s Open method or either instance of the SqlCommand object’s ExecuteNonQuery method, then the code in the Catch block will be executed, and a message box will be displayed showing the text of the exception condition.

    At the end of the CommandNonQuery subroutine, the SqlConnection object’s Close method is executed to end the connection to the SQL Server database.

    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