ASP.NET
  Home arrow ASP.NET arrow Page 4 - Object-Oriented Programming Applied: A Cus...
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

Object-Oriented Programming Applied: A Custom Data Class
By: Addison-Wesley/Prentice Hall PTR
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 6
    2005-08-11

    Table of Contents:
  • Object-Oriented Programming Applied: A Custom Data Class
  • Analyzing Design Requirements
  • The Constructors
  • Create, Update, and Delete Methods
  • Caching the Data for Better Performance
  • Getting More than One Record at a Time
  • Summary

  • 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


    Object-Oriented Programming Applied: A Custom Data Class - Create, Update, and Delete Methods


    (Page 4 of 7 )

    In the example we gave at the beginning of the chapter, we created a Customer object using the default constructor, assigned some properties, and then called a Create() method. This Create() method takes all of the current property values and inserts them into their corresponding columns in a new row in the Customers table. Again, the code in Listing 5.6 should be very familiar to you.

    Listing 5.6 The Create() method

    C#
    public int Create()
    {
      SqlConnection connection = new SqlConnection(_ConnectionString);
      connection.Open();
      SqlCommand command = new SqlCommand("INSERT INTO Customers "
        + "(LastName, FirstName, Address, City, State, Zip, Phone, "
        + "SignUpDate) VALUES (@LastName, @FirstName, @Address, "
        + "@City, @State, @Zip, @Phone, @SignUpDate)",
        connection);
      command.Parameters.AddWithValue("@LastName", _LastName);
      command.Parameters.AddWithValue("@FirstName", _FirstName);
      command.Parameters.AddWithValue("@Address", _Address);
      command.Parameters.AddWithValue("@City", _City);
      command.Parameters.AddWithValue("@State", _State);
      command.Parameters.AddWithValue("@Zip", _Zip);
      command.Parameters.AddWithValue("@Phone", _Phone);
      command.Parameters.AddWithValue("@SignUpDate", _SignUpDate);
      command.ExecuteNonQuery();
      command.Parameters.Clear();
      command.CommandText = "SELECT @@IDENTITY";
      int newCustomerID = Convert.ToInt32(command.ExecuteScalar());
      connection.Close();
      _CustomerID = newCustomerID;
      return newCustomerID;
    }

    VB.NET
    Public Function Create() As Integer
      Dim connection As New SqlConnection(_ConnectionString)
      connection.Open()
      Dim command As New SqlCommand("INSERT INTO Customers " _
        & "(LastName, FirstName, Address, City, State, Zip, Phone, "_
        & "SignUpDate) VALUES (@LastName, @FirstName, @Address, @City, "_
        & "@State, @Zip, @Phone, @SignUpDate)", connection)
      command.Parameters.AddWithValue("@LastName", _LastName)
      command.Parameters.AddWithValue("@FirstName", _FirstName)
      command.Parameters.AddWithValue("@Address", _Address)
      command.Parameters.AddWithValue("@City", _City)
      command.Parameters.AddWithValue("@State", _State)
      command.Parameters.AddWithValue("@Zip", _Zip)
      command.Parameters.AddWithValue("@Phone", _Phone)
      command.Parameters.AddWithValue("@SignUpDate", _SignUpDate)
      command.ExecuteNonQuery()
      command.Parameters.Clear()
      command.CommandText = "SELECT @@IDENTITY"
      Dim newCustomerID As Integer = _
        Convert.ToInt32(command.ExecuteScalar())
      connection.Close()
      _CustomerID = newCustomerID
      Return newCustomerID
    End Function

    Generally when we create a record in the database, we’re done with it, and we move on to other things. However, just in case, we’ve added an extra step to our Create() method. We’re going back to the database to see what the value is in the CustomerID column of the new record we’ve created, using the SQL statement “SELECT @@IDENTITY.” We’re assigning that value to the CustomerID property of our class and sending it back as the return value of our method. Given the design parameter decision we made earlier, changing the CustomerID value to anything other than 0 means that it corresponds to an actual record in the database.

    Going back again to the ?rst code sample, we’ll use a method called Update() to change the data in a speci?c row of our database table. That method is shown in Listing 5.7.

    Listing 5.7 The Update() method

    C#
    public bool Update()
    {
      if (_CustomerID == 0) throw new Exception("Record does not exist in Customers table.");
      SqlConnection connection = new SqlConnection(_ConnectionString);
        connection.Open();
      SqlCommand command = new SqlCommand("UPDATE Customers SET "
        + "LastName = @LastName, FirstName = @FirstName, "
        + "Address = @Address, City = @City, State = @State, "
        + "Zip = @Zip, Phone = @Phone, SignUpDate = @SignUpDate "
        + "WHERE CustomerID = @CustomerID", connection);
      command.Parameters.AddWithValue("@LastName", _LastName);
      command.Parameters.AddWithValue("@FirstName", _FirstName);
      command.Parameters.AddWithValue("@Address", _Address);
      command.Parameters.AddWithValue("@City", _City);
      command.Parameters.AddWithValue("@State", _State);
      command.Parameters.AddWithValue("@Zip", _Zip);
      command.Parameters.AddWithValue("@Phone", _Phone);
      command.Parameters.AddWithValue("@SignUpDate", _SignUpDate);
      command.Parameters.AddWithValue("@CustomerID", _CustomerID);
      bool result = false;
      if (command.ExecuteNonQuery() > 0) result = true;
      connection.Close();
      return result;
    }

    VB.NET
    Public Function Update() As Boolean
      If _CustomerID = 0 Then Throw New Exception("Record does not exist in Customers table.")
      Dim connection As New SqlConnection(_ConnectionString)
      connection.Open()
      Dim command As New SqlCommand("UPDATE Customers SET "_
        & "LastName = @LastName, FirstName = @FirstName, "_
        & "Address = @Address, City = @City, State = @State, "_
        & "Zip = @Zip, Phone = @Phone, SignUpDate = @SignUpDate "_
        & "WHERE CustomerID = @CustomerID", connection)
      command.Parameters.AddWithValue("@LastName", _LastName)
      command.Parameters.AddWithValue("@FirstName", _FirstName)
      command.Parameters.AddWithValue("@Address", _Address)
      command.Parameters.AddWithValue("@City", _City)
      command.Parameters.AddWithValue("@State", _State)
      command.Parameters.AddWithValue("@Zip", _Zip)
      command.Parameters.AddWithValue("@Phone", _Phone)
      command.Parameters.AddWithValue("@SignUpDate", _SignUpDate)
      command.Parameters.AddWithValue("@CustomerID", _CustomerID)
      Dim result As Boolean = False
      If command.ExecuteNonQuery() > 0 Then result = True
      connection.Close()
      Return result
    End Function

    We start our Update() method with a check of the CustomerID value. If it’s 0, we know that the object does not correspond to an existing record in the database, so we throw an exception. If the code is allowed to continue, the rest includes the familiar connection and command objects, as well as parameters that take the current values of our properties and use them to update our database record.

    The last few lines are used to check for a successful update of the database. The ExecuteNonQuery() method of the command object returns an integer indicating the number of rows affected by our command. Because our WHERE clause is matching the CustomerID column, a column that we know must have a unique value, the only thing we’re interested in knowing is that at least one row was affected. If a value greater than 0 is returned from ExecuteNonQuery(), then we return a Boolean true value back to the calling code. This enables us to con?rm that the data was indeed updated.

    Where we can create and update data, we can also delete it. Enter our Delete() method in Listing 5.8, the simplest of the lot.

    Listing 5.8 The Delete() method

    C#
    public void Delete()
    {
      SqlConnection connection = new SqlConnection(_ConnectionString);
      connection.Open();
      SqlCommand command = new SqlCommand("DELETE FROM Customers "
        + "WHERE CustomerID = @CustomerID", connection);
      command.Parameters.AddWithValue("@CustomerID", _CustomerID);
      command.ExecuteNonQuery();
      connection.Close();
      _CustomerID = 0;
    }

    VB.NET
    Public Sub Delete()
      Dim connection As New SqlConnection(_ConnectionString)
      connection.Open()
      Dim command As New SqlCommand("DELETE FROM Customers "_
        & "WHERE CustomerID = @CustomerID", connection)
      command.Parameters.AddWithValue("@CustomerID", _CustomerID)
      command.ExecuteNonQuery()
      connection.Close()
      _CustomerID = 0
    End Sub

    There isn’t anything complex about this code. We create our connection object and command objects, use the current value of the CustomerID property to make our match in our SQL statement, and execute the command. Just in case the calling code decides it wants to do something with the data, such as call the object’s Update() method against a record that no longer exists, we set the CustomerID property back to 0.

    More ASP.NET Articles
    More By Addison-Wesley/Prentice Hall PTR


       · Great article! I can never over emphasize the importance of a good data abstraction...
       · Great Article!!
     

    Buy this book now. This article is excerpted from chapter five of the book Maximizing ASP.NET: Real World, Object-Oriented Development, written by Jeffery Putz (Addison-Wesley Professional, 2005; ISBN: 0321294475). Check it out at your favorite bookstore. Buy this book now.

    ASP.NET ARTICLES

    - Developing a Mini ASP.NET AJAX Server Centri...
    - 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

     
    Best Practices for Windows Vista Migration Presentation
    Dell and Microsoft recently held a series of face-to-face seminars entitled, &qu....

     
    Creating a Culture for Code Reuse
    If you oversee development teams you know that like it or not proprietary and ex....

     
    Keys to Web Application Acceleration: Advances in Delivery Systems
    Accelerate Web apps by up to 5x. Ensure significantly faster access to the Web a....

     
    Optimizing Application Monitoring
    Tired of finding out from your customers that you're offline? This white paper e....

     
    Solaris to Solaris Migration -- Migrating applications from Sun SPARC to Dell PowerEdge R900
    This comprehensive Migration Guide reviews the approach that Principled Technolo....

     




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