ASP.NET
  Home arrow ASP.NET arrow Page 2 - Updating and Inserting Data with ADO.NET a...
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? 
ASP.NET

Updating and Inserting Data with ADO.NET and ASP.NET 2.0
By: Michael Youssef
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 5
    2007-09-24

    Table of Contents:
  • Updating and Inserting Data with ADO.NET and ASP.NET 2.0
  • Closing SqlConnection and SqlDataReader objects through the using block
  • Inserting and Updating Data using the SqlCommand
  • Using Parameterized Queries to Retrieve Data

  • 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


    Updating and Inserting Data with ADO.NET and ASP.NET 2.0 - Closing SqlConnection and SqlDataReader objects through the using block


    (Page 2 of 4 )

    In C# we can make sure that any object that has a Dispose() method, by implementing the IDisposable interface, can be disposed of with the using block. The using block is passed a reference to an object that is used inside the block;  when the execution of the block's code completes, the object's Dispose() method is called. Note that the Dispose() method will also be called in the event of an exception; in fact the Dispose() method will be called no matter what happens. Both the SqlConnection and the SqlDataReader implement the IDisposable interface so they have a Dispose() method defined and implemented. The Dispose() method implicitly calls the Close() method which is exactly what we need. Let's see the modified version of the above example that uses this technique.

    Replace the Page_Load() event handler with the following:

    protected void Page_Load(object sender, EventArgs e){
      // create the connection and set the connection string
      // through the connection object's constructor
      string connectionString = "Data Source=(local);
      Initial Catalog=Northwind;Integrated Security=True";
      SqlConnection connection = new SqlConnection(connectionString);

      // create the command object and the T-SQL SELECT statement
      // and assign the connection object along with the T-SQL
      // SELECT statement to command object through the constructor
      string commandText = "SELECT LastName, FirstName FROM
    Employees";
      SqlCommand command = new SqlCommand(commandText, connection);

      // we have initialized the connection and the command so it's
      // time to open the connection and execute the command
      // using a try/catch block to handle exceptions
      SqlDataReader dataReader;
      try{
        // check if the connection is already open
        if (connection.State == ConnectionState.Closed){
          connection.Open();
        }
        // make sure that the connection is closed after we finish
        // using it
        using (connection){
          // get a SqlDataReader object from the Command's 
          // ExecuteReader() method and make sure that the data 
          // reader is closed too
          using (dataReader = command.ExecuteReader()){
            // adding the returned rows to the listbox control
            while (dataReader.Read()){
              ListBox1.Items.Add(dataReader["LastName"] + ", " +
    dataReader["FirstName"]);
            }
          }
        }
      }
      catch (Exception ex){
        Label1.Text = ex.Message;
      }
    }

    What we have added in this example is two using blocks, one for the connection object and the other for the data reader object. Note that you can create the object with the using block like so:

    using(SqlConnection connection = new SqlConnection(connectionString)){
      connection.Open();
      // execute the command and return the data reader

    // here the SqlConnection.Dispose() method will be called 
    // which in turn calls the SqlConnection.Close() method

    But in our example we passed a reference to the connection object because we wanted to test whether or not the connection is open before we use it. We have also used another nested using block with the data reader object to make sure that it's closed when we finish using it. Actually if we don't close the SqlDataReader object, the SqlConnection object can't be used for anything else because it's busy serving the SqlDataReader object, so it's very important to close the SqlDataReader object. We have removed the finally block because it's not needed anymore; we have the using block which closes the connection, and the data reader, when it finishes executing its statements.

    More ASP.NET Articles
    More By Michael Youssef


       · Before reading this article, please read the article Introducing ADO.NET with...
     

    ASP.NET ARTICLES

    - Disadvantages of the ASP.NET MVC Framework
    - Advantages of the ASP.NET MVC Approach
    - ASP.NET Web Forms Weaknesses
    - ASP.NET Web Forms Meets ASP.NET MVC
    - Source Code for Saving and Retrieving Data w...
    - Using GridView to Save and Retrieve Data wit...
    - Handling Dynamic Images in ASP.NET 3.5 AJAX ...
    - Retrieving Data with AJAX and the GridView C...
    - Playing with Images in ASP.NET 3.5 AJAX Appl...
    - Saving and Retrieving Data with AJAX
    - Enhancing PHP Via the ASP.NET AJAX Framework...
    - Enhancing PHP Programming with the ASP.NET A...
    - Classes and ASP.NET AJAX
    - Using ASP.NET AJAX
    - Building a Simple Storefront with LINQ

     
    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 6 hosted by Hostway
    Stay green...Green IT