Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
This chapter is from the book

Retrieving Data with ADO.NET

Despite the similarity in the name, ADO.NET is something totally different from classic ADO on the unmanaged platform. For instance, it does not include a Recordset object, and the Excel CopyFromRecordset method is not supported. This is covered in more detail in Chapter 25, "Writing Managed COM Add-ins with VB.NET." Another major difference is that ADO.NET has strong support for XML data representation. VS 2008 ships with version 3.5 of the ADO.NET class library.

ADO.NET is one of the default namespaces included in all Windows Forms based solutions, so to use it we just need to add Imports statements to the top of code modules from which ADO.NET will be called. However, to complicate things ADO.NET can be used in two different ways: connected mode and disconnected mode.

Before we can examine these two different approaches we need to first discuss .NET Data Providers. Data providers are used to connect to databases, execute commands, and provide us with the results. Each database, like SQL Server, Oracle, MySQL, and so on requires its own unique data provider. Some data providers are available by default in the .NET Framework, including SQL Server, Oracle, and OLE DB. Other data providers can be obtained from specific database vendors. For Microsoft Access and other databases that support ODBC, the OLE DB Data Provider can be used.

Connected mode means that we work with an open connection to the database. In this mode we explicitly use command objects and the DataReader object. A DataReader object retrieves a read-only, forward-only stream of data from a database. It can also handle multiple result sets. To do this, the connection must be open during the whole data retrieval process. Connected mode provides a performance advantage if we need to work with database records one at a time because the DataReader object retrieves and stores them in memory. However, the drawback is that connected mode creates more network traffic and requires having an active connection open during the whole database operation.

In Listing 24-30, we use a SQL Server database and therefore we import the namespace System.Data.SqlClient, which gives us access to the .NET Data Provider for SQL Server. We also use the ADO.NET class library and therefore we import the namespace System.Data.

Listing 24-30. Using a DataReader Object

'At the top of the code module.
Imports System.Data
Imports System.Data.SqlClient

Friend Function Retrieve_Data_With_DataReader() As ArrayList

         'SQL query in use.
         Const sSqlQuery As String = _
              "SELECT CompanyName AS Company " & _
              "FROM Customers " & _
              "ORDER BY CompanyName;"

        'Connection string in use.
        Const sConnection As String = _
            "Data Source=PED\SQLEXPRESS;" & _
            "Initial Catalog=Northwind;" & _
            "Integrated Security=True"

        'Declare and initialize the connection.
        Dim sqlCon As New SqlConnection(connectionString:= _
        'Declare and initialize the command.
        Dim sqlCmd As New SqlCommand(cmdText:=sSqlQuery, _
        'Define the command type.
        sqlCmd.CommandType = CommandType.Text

        'Explicitly open the connection.

        'Populate the DataReader with data and
        'explicit close the connection.
        Dim sqlDataReader As SqlDataReader = _
        sqlCmd.ExecuteReader(behavior:= _

        'Variable for keeping track of number of rows in the
        Dim iRecordCounter As Integer = Nothing

        'Get the number of columns in the DataReader.
        Dim iColumnsCount As Integer = sqlDataReader.FieldCount

        'Declare and instantiate the ArrayList.
        Dim DataArrLst As New ArrayList

        'Check to see that it has at least one
        'record included.
        If sqlDataReader.HasRows Then

            'Iterate through the collection of records.
            While sqlDataReader.Read

                For iRecordCounter = 0 To iColumnsCount - 1

                    'Add data to the ArrayList's variable.
                    DataArrLst.Add(sqlDataReader.Item _

                Next iRecordCounter

            End While
        End If

        'Clean up by disposing objects, closing and
        'releasing variables.
        sqlCmd = Nothing

        sqlDataReader = Nothing

        sqlCon = Nothing

        'Send the list to the calling method.
        Return DataArrLst

End Function

We first create a SqlConnection object and then a SqlCommand object. Next we explicitly open the connection, create the DataReader object, and iterate through the collection of records in the DataReader object by using its Read method. Within the loop we populate an ArrayList object with the data from the DataReader object. Finally, we close and clean up the objects we've used and return the data in the ArrayList to the calling method. The Northwind database used in this example can be found on the companion CD in \Applications\Ch24 - Excel & VB.NET \Northwind.

When working in disconnected mode we make use of the DataAdapter, DataSet, and DataTable objects, which are supported by all .NET Data Providers. A DataAdapter acquires the data from the database and populates the DataTable(s) in a DataSet. The DataAdapter object includes commands to automatically connect to and disconnect from the database. It also includes commands to select, insert, update, and delete data. The DataAdapter object runs these commands automatically. The DataSet is an in-memory representation of the data, and like the DataReader object it can handle multiple SQL queries at the same time.

The advantages of using disconnected mode are that it creates less network traffic because it acquires the data in one go, and it does not require an open connection to the database once the data has been retrieved. It also allows us to first update the retrieved data and then return the updated data to the database.

Listing 24-31 shows a complete function, including SEH, which first creates the Connection object together with the DataAdapter object. It then creates and initializes a new DataSet. Next it initializes the DataAdapter object, which automatically establishes a connection, retrieves the data, and closes the connection. The DataSet is filled with the retrieved data and finally the function returns the first DataTable in the DataSet.

Listing 24-31. Using DataAdapter and DataSet Objects

'On top of the code module.
Imports System.Data
Imports System.Data.SqlClient

    Friend Function Retrieve_Data_With_DataAdapter() As DataTable

        'SQL query in use.
        Const sSqlQuery As String = _
            "SELECT CompanyName AS Company " & _
            "FROM Customers " & _
            "ORDER BY CompanyName;"

        'Connection string in use.
        Const sConnection As String = _
            "Data Source=PED\SQLEXPRESS;" & _
            "Initial Catalog=Northwind;" & _
            "Integrated Security=True"

        'Declare the connection variable.
        Dim SqlCon As SqlConnection = Nothing

        'Declare the DataAdapter variable.
        Dim SqlAdp As SqlDataAdapter = Nothing

        'Declare and initialize a new empty DataSet.
        Dim SqlDataSet As New DataSet

            'Initialize the connection.
            SqlCon = New SqlConnection(connectionString:= _
            'Initialize the DataAdapter.
            SqlAdp = New SqlDataAdapter(selectCommandText:= _
                                           sSqlQuery, _
                                           selectConnection:= _

            'Fill the DataSet.
            SqlAdp.Fill(dataSet:=SqlDataSet, srcTable:="PED")

            'Return the datatable.
            Return SqlDataSet.Tables(0)

        Catch Sqlex As SqlException
            'Exception handling for the communication with
            'the SQL Server Database.

            'Tell it to the calling method.
            Return Nothing


            'Releases all resources the variable has consumed from
            'the memory.

            'Release the reference the variable holds and
            'prepare it to be collected by the Garbage Collector
            '(GC) when it comes around.
            SqlDataSet = Nothing

            SqlCon = Nothing

            SqlAdp = Nothing

        End Try

    End Function

The function returns a DataTable object from the ADO.NET class, but we do not need to cast it into a DataTable object from the DataSet class before returning it. The exception handler catches any exceptions that occur in the SQL Server Data Provider. In the Finally block we dispose all object variables and set them to nothing. A working example of this solution can be found on the companion CD in \Concepts\Ch24 - Excel & VB.NET\Northwind folder.

ADO.NET may be a new technology for developers who are working with the .NET platform for the first time. But for Microsoft, the latest technology is .NET Language Integrated Query (LINQ), which is part of the .NET Framework 3.5 and was released with VS 2008. LINQ is a set of .NET technologies that provide built-in language querying functionality similar to SQL for accessing data from any data source. Instead of using string expressions that represent SQL queries, we can use a rich SQL-like syntax directly in our VB.NET code to query databases, collections of objects, XML documents, and more.

The future will tell us more about how well LINQ will succeed. Developers who are coming from classic ADO are more likely to first adopt ADO.NET and later perhaps also begin to use LINQ.

  • + Share This
  • 🔖 Save To Your Account