Rick Dobson
When it comes to database connections, .NET proponents like to highlight the benefits of the disconnected access provided by Data Adapters and Data Sets. In the process, the DataReader sometimes gets swept under the rug. But, as Rick Dobson demonstrates here, DataReaders are different-they provide forward-only, read-only, connected access to data sources, and they do not support data manipulation So why would you want to use something that limits you so much Performance, for starters:.? DataReaders are much faster . Another benefit is a smaller memory footprint-DataReaders allow you to work with data as you get it, a row at a time. So DataReaders are particularly well-suited for working with data that's too large to fit in memory comfortably.
In order to gain the best advantage from DataReaders, you need to understand their capabilities and limitations. Because DataReaders have well-defined limits, you can also benefit from an understanding of how to tap other .NET entities, such as arrays, to complement DataReader features. This article reviews DataReader capabilities with a couple of sample applications in each of three areas. First, I present efficient code patterns for generating, populating, and configuring DataReaders for use with Windows Forms controls. The second pair of samples highlights how you can Work with Typed Data To Compute Exputes, Which Reflect The Nature of the Data Types for the columns in a DataReader. i close by Contrasting Tw Techniques for Retrieving Hierarchical Data Via DataReaders.
From DataReader to listboxYou can easily populate a listbox with a DataReader that's pointed at a data source. This section's samples generally apply to combo box controls as well. You begin by creating the DataReader and invoking the ExecuteReader method for a Command object, usually created in -line.The ExecuteReader method can accept CommandBehavior enumerations to customize the Command's behavior and its associated DataReader. The two samples in this section highlight the interplay between DataReaders and their Command objects, and provide other interesting application details pertaining to form and control management. See The Hcvsdataareaders Project To Access All of the code for each sample.
Displaying Raw DataReader Data
The first DataReader sample in the HCVSDataReaders project is in the Click event for Button1 on Form1 along, with two methods in the ADONETObjects class and the DataReaderForTable function procedure behind Form1. For convenience, the ADONETObjects class resides in the HCVSDataReaders project. Figure 1 shows the form after a click to the button with the label Populate from DataReader. The Click event procedure for the button populates the listbox with selected column values from the Employees table in the SQL Server Northwind database.
The SqlDataReader class has many special methods for getting data in all kinds of specialized .NET and SQL Server data formats. However, for simple applications, you do not have to worry about them. All the DataReader needs to do is accept the default conversion from any non-string data type to a string and then add a computed string expression to the listbox. that's what the following code does. It's from the Button1_Click procedure. A While loop reads row after row, each time creating a str2 expression that includes four references to the drd1 DataReader. Two of these references are for numeric instances. And it's even possible that a value may be null (as is the case with the ReportsTo column value for employee number 2). nevertheless, the expression succeeds for every row YOU CAN Designate Column Either by name or by a zero-based index.do while DRD1.READ
DIM str2 as string = _
"Employee" & DRD1 ("EmployeeID") & _
"," & DRD1 ("firstname") & _
"" "Lastname") & _
"Reports to:" & DRD1 ("Reportsto")
ListBox1.Items.Add (str2)
Loop
Perhaps the most interesting element of the first sample is how it creates the drd1 DataReader in the first place. Button1's Click event procedure creates drd1 as a SqlDataReader class and assigns it the return value from a function I created called DataReaderForTable. It passes the name of The Table, Employees, for Which DataReaderfortable Develops a DataReader.
DIM DRD1 AS SQLCLIENT.SQLDATAREADER = _
DataReaderfortable ("EMPLOYEES")
The DataReaderfortable Procedure Creates A DataReader in Three Steps.
DIM DRD1 As SqlClient.sqldataReader
Dim Adoobjs As New AdonEtObjects'Specify Connection Object
DIM CNN1 As SqlClient.sqlConnection = _
Adoobjs.makenorthWindConnection
'Specify A Command Object
DIM str1 as string = _
"Select * from" & TableName
DIM CMD1 AS _
Sqlclient.sqlcommand = _
Adoobjs.makeacommand (CNN1, STR1)
'Open CNN1 and CREATE THE DRD1 DATAREADER
'with the executereader method cnn1.open ()
DRD1 = cmd1.executeReader_
(Commandbehavior.CloseConnection)
Return DRD1
First, it creates a connection to the Northwind database with the MakeNorthwindConnection method from my ADONETObjects class. Next, I create a Command object for the DataReader. The DataReaderForTable procedure passes two arguments to my ADONETObjects' MakeACommand method to return a new Command object. The arguments are for the SQL statement that extracts all columns for all rows in the TableName argument passed to the DataReaderForTable procedure and the Connection object returned by the MakeNorthwindConnection method.
In the third step, the procedure actually creates the DataReader with the ExcecuteReader method for the Command object. The use of the CommandBehavior.CloseConnection enumeration makes it possible for the Button1_Click procedure to close a DataReader returned to it without also needing to manipulate the associated Connection object. This is because the enumeration instructs the .NET Framework to automatically close the Connection object when the DataReader closes. The DataReaderForTable procedure concludes by returning the instantiated DataReader.
By The Way, The DataReaderfortable Procedure Has A Shared Access Mode Decaration So That Procedures in Other Modules Throughout The Hcvsdataareaders Project Can Call It.Processing DataReader Data
There are at least a couple of areas in which ListBox1's contents can improve. First, there's no EmployeeID value to denote to whom Andrew Fuller reports. This is not an error, because he reports to no one else in the listbox. Still, it's potentially confusing to have a blank. Second, ListBox1 designates an employee's manager by the manager's EmployeeID. The readability of the ListBox1 contents can improve by replacing the manager's EmployeeID with the manager's last name.
The Button2_Click procedure populates ListBox1 in a way that handles both of the problems with the Button1_Click procedure. Figure 2 shows the improved output after a click to the button labeled Populate from array. The line for the employee named Andrew Fuller indicates he has no supervisors in ..........................
One of the main challenges in transforming the supervisor EmployeeID column values to last names is that the DataReader only knows about one row for an employee at a time. In order to transform the supervisor EmployeeID column value, an application needs to link each EmployeeID value to a last name. by storing values from the DataReader in an array of strings, procedures can look up the last name that matches an EmployeeID value. (of course, this particular problem could also be solved by creating a more complex Select statement in the query , but for the purposes of demonstrating the use of arrays with DataReaders, I'll show you how to solve this problem on the client side.) The following code segment from the Button2_Click procedure shows how to populate the MyEmps array of string values with values From The DRD1 DataReader, Which Was Defined The Same Way AS in Button1_Click.
Const RowsCount as integer = 99
DIM Myemps (RowsCount, 3) AS String
Do while DRD1.READ
IF INT1 <= ROWSCOUNT THEN
For int2 = 0 to DRD1.FIELDCOUNT () - 1
SELECT CASE DRD1.GETNAME (INT2)
Case "Employeeid"
Myemps (INT1, 0) = DRD1 (INT2)
Case "firstname"
Myemps (INT1, 1) = DRD1 (INT2)
Case "lastname"
Myemps (INT1, 2) = DRD1 (INT2)
Case "Reportsto"
'TOSTRING METHOD FORCES Conversion -
'Even for dbnull value to string
Myemps (INT1, 3) = DRD1 (INT2) .tostring
End SELECT
NEXT
INT1 = 1
Else
Messagebox.show (_
"RESET ROWSCOUNT to A Larger Number and RE-RUN.", _
"Terminal Error Message", _
MessageboxButtons.ok, MessageBoxicon.exclamation
EXIT SUB
END IF
Loop
The MyEmps array has four columns for EmployeeID, FirstName, LastName, and ReportsTo column values. Its maximum row specification is more than sufficient for the default number of nine rows in the Northwind database. The While loop for reading rows has code in it to perform different kinds of tasks.A for loop iterates through all of the column values to select a subset of DataReader column values for storage in MyEmps. The FieldCount property returns the number of columns in the DataReader. A Select ... End Select statement examines column .
With the exception of the ReportsTo column values, the code applies the default Visual Basic .NET conversion from a SQL Server data format to a .NET string format in the MyEmps array. Because the ReportsTo column could include a null value (DBNULL), the Procedure Must Explicitly Specify The Tostring Method for Forcing The DBNULL TO A STRING VALUE-NAMELY, An Empty String ("").
After collecting all of the drd1 column values in the MyEmps array, Button2_Click closes the DataReader and frees those resources. The next major code segment, which appears below, loops through the rows of MyEmps to compute string expressions for display in ListBox1. Instead of just showing the raw ReportsTo column value for a row, the code loops a second time through the MyEmps array to find a LastName column value that matches the ReportsTo column value. Before entering the loop to decode a ReportsTo column value to a LastName column value, the Code Ascertains WHether The Reportsto Value In The Fourth Column Is An Empty String.
For int1 = 0 to 99
IF myemps (INT1, 0) <> "" "
IF MyEmps (INT1, 3) <> "" "" "
strsupvrempid = myemps (INT1, 3)
For int2 = myemps.getLowerBound (0) to _
Myemps.getupperbound (0)
IF myemps (int2, 0) = strsupvrempid then
strempid = myemps (INT2, 2)
EXIT for
END IF
NEXT
Else
strempid = "no one in list box"
END IF
Str1 = "Employeeid" & myemps (INT1, 0) & _
"," & Myemps (INT1, 1) & "& _
Myemps (INT1, 2) & "Reports TO:" & _
strempid
ListBox1.Items.add (str1)
Else
EXIT for
END IF
NEXT
Processing Typed Data
The application for Form1 converted the contents of each DataReader column to a string value-no matter what the underlying data type for a column in a data source. There are times when you need to work with original data types, such as when you need to Perform Numeric or Date Arithmetic with column values. If you don't alleady know the Underly NEED A TECHNIQUE To Discover Original Data Types Before Using Them IN Expressions.
Reporting Column Names and Data Types
The Button1_Click procedure in Form2 demonstrates a technique for writing out the column names and data types of any DataReader. While .NET offers other approaches to this task, this technique builds on your understanding of DataReaders and how to use them with arrays. The procedure starts by creating a DataReader for the Orders table in the Northwind database based on the DataReaderForTable procedure in Form1 Since the DataReaderForTable procedure was declared with a Shared access mode, Form2 can invoke with the following.:
DIM DRD1 AS SQLCLIENT.SQLDATAREADER = _
Form1.DataReaderfortable ("ORDERS")
You also need an array to hold the column names and data types for the drd1 DataReader. The array columns will hold the string values designating the names of columns and their data types for the drd1 DataReader. The following code excerpt shows how to apply the CreateInstance Shared method for the Array class to create an array named OrdersColNamesTypes. This array has as many rows as there are columns in the drd1 DataReader and two columns. A for loop iterates through the columns of the DataReader to populate the array with column name and data type metadata. The SetValue method assigns values to array elements. You learned from the preceding sample how to use the GetName method to return column names. This procedure illustrates how to apply the GetDataTypeName method to recover the native data type name for a column in a DataReader.dim ORDERSCOLNAMESTYPES as array = _
Array.createInstance (Gettype (String), _
DRD1.FIELDCOUNT, 2)
For Int1 as integer = 0 to DRD1.FIELDCOUNT - 1
ORDERSCOLNAMESTYPES.SETVALUE
(DRD1.GETNAME (INT1), INT1, 0)
ORDERSCOLNAMESTYPES.SETVALUE
(DRD1.GETDATATIPENAME (INT1), INT1, 1)
NEXT
The final code segment for the Button1_Click procedure on Form2 merely loops through the column values for each successive row in the array OrdersColNamesTypes and prints to the Output window the column names and data types, as you can see in Figure 3. The report in the figure indicates that the Order table has 14 columns. The Order table's first column has a name of OrderID and a SQL Server int data type. Other columns have variable and fixed length string data types (nvarchar and nchar) as well as datetime and money data types .
Performing Arithmetic
The trick to performing arithmetic with DataReader column values is to save them in a Visual Basic .NET data type that matches their native database data type. However, arrays force all element members to the same type. One way to use an array to store values from a DataReader, but still maintain the data source's data types, is to save the DataReader column values to an array with Object data type elements. This process essentially boxes the DataReader column values as Object instances that do not coerce them to another data type . You can later recover the basic underlying data format by assigning the array elements to a variable declared with an appropriate data type. This assignment essentially unboxes the data type.The code behind Form2 includes a procedure, PopArray, that boxes DataReader column values in an Array with Object Elements. View The Listing for PopArray In The HcvsDataReaders Project If You're Intested in The Details of this process.
One main purpose of the PopArray procedure in this article is to enable the demonstration of integer and datetime arithmetic with column values from the Orders table in a Windows application. Form2's Button2_Click procedure has two main code segments. The first demonstrates how to compute the difference between the OrderID column values for the first and last rows in the Orders array, which mirrors the Orders table in the Northwind database. Before starting the first main segment, the procedure invokes the PopArray procedure to populate the Orders array. in case you're wondering , the Orders table has 830 rows. Two assignments for variables named int1 and int2 unbox the OrderID column value for the first and last row in the first column of the Orders array. The arguments for the WriteLine method include a simple expression that subtracts one Integer Variable from another.dim ORDERS As Array = PopArray ("Orders", 830)
DIM INT1 AS INTEGER = _
Orders (ORDERS.GETLOWERBOUND (0), _
ORDERS.GETLOWERBOUND (1))
DIM INT2 AS Integer = _
Orders (ORDERS.GetupperBound (0), _
ORDERS.GETLOWERBOUND (1))
Console.writeline (ControlChars.crlf & _
"AN EXAMPLE with INTEGER ARITHMETIC:")
Console.writeline (_
"There is {2} Order NumBers Between" & _
"THE FIRST ORDER NUMBER ({0}) and the" & _
"Last ORDER NUMBER ({1})", _
INT1, INT2, INT2 - INT1)
Button2_Click's second main code segment performs datetime arithmetic with the ShippedDate and RequiredDate column values in the first row of the Orders array. Instead of unboxing the Object elements to variables with Integer data types, this code unboxes the two columns to Date data types. You can use Date and datetime keywords interchangeably to designate datetime values in Visual Basic .NET. A DateDiff function computes the difference in days between the two datetime variables. The WriteLine method for the Console class displays the result in the Output window.'Demonstrate arithmetic with dates
DIM DATREQUIRED AS DATE = Orders (0, 4)
DIM DATSHIPPED As Date = Orders (0, 5)
Console.writeline (ControlChars.crlf & _
"An Example with Date Arithmetic")
Console.writeline (_
"Required Date ({1}) - ShippedDate ({0})" & _
"= {2} days", _
Datshipped.toString ("m / d / yyyy"), _
DATREQUIRED.TOSTRING ("m / d / yyyyy"), _
DateDiff (DateInterVal.day, Datshipped, _
DATREQUIRED))
Generating Hierarchical Data
It's very common for applications to require hierarchical data, such as the line items that belong to an order. My last two samples present two tactics for returning hierarchical data via a DataReader. One approach demonstrates the use of the specialized MSDataShape provider. The second approach uses more general tools based on those presented earlier in this article. in addition, the second technique builds on the first one by adding a lookup feature for values in a related table and illustrating formatting syntax for datetime and currency values.
Using the MSDatahape Provider
As I indicated earlier, the MSDataShape provider is a specialized provider for returning hierarchical data. This provider dates back to Visual Basic 6, but Microsoft issued a Knowledge Base article describing how to use the MSDataShape provider with Visual Basic .NET and ADO.NET ( http://support.microsoft.com/default.aspx?scid=kb;[LN];308045). While the MSDataShape provider is exceptionally efficient at returning hierarchical result sets, the provider relies on a subset of SQL along with specialized keywords and other syntax conventions. In addition, this provider does not work with the .NET SQL Server data provider. Instead, you're forced to use the OleDb .NET data provider-even when working with a SQL Server database.Making a connection to the database using the MSDataShape provider is a little different. The following code is from the Button1_Click procedure in Form3. Notice that the code designates a Connection object in the OleDb namespace. While the last three arguments for server, integrated security, and initial catalog are shared in common with those for a SqlConnection object connection string, the initial two arguments are distinct. The very first argument designates the MSDataShape provider, which works in concert with the SQLOLEDB data provider that's specified in the second argument .
New oledb.oledbconnection (_
"Provider = msdatashape; data provider = sqloledb;" & _
"Server = (local); integrated security = sspi;" & _
"Initial Catalog = Northwind")
................... ..
DIM cmd1 as oledb.oledbcommand = _
New oledb.oledbcommand (_
"Shape {Select ORDERID, OrderDate" & _
"From Orders" & _
"Where orderid =" & textbox1.text & "}" & _
Append ({Select OrderID, ProductID, "& _
"Unitprice, Quantity, Discount" & _
"From [Order Details]} & _
"Relate Orderid to Orderid", CNN1)
CNN1.Open ()
DIM DRD1 AS OLEDB.OLEDBDATAREADER = _
cmd1.executeReader (Commandbehavior.CloseConnection)
DRD1.READ ()
Console.writeLine ("{0}, {1}", _
DRD1 (0), DRD1 (1))
DIM DRD2 AS OLEDB.OLEDBDATAREADER = DRD1 (2)
Do while DRD2.READ
Console.writeline ("{0}, {1}, {2}, {3}, {4}", _
DRD2 (0), DRD2 (1), DRD2 (2), DRD2 (3), DRD2 (4)))
Loop
Notice the specialized keywords of SHAPE, APPEND, and RELATE. The SQL statement for the SHAPE clause designates the row for the master result set. This statement references TextBox1's Text property, which should always specify a valid OrderID column value. The SQL statement for the Append Clause Designates The Result Set for the detail Member of the Hierarchical Result Set. The Relate Clause Indicates The Columns on Which To Match Rows in The Master and Detail Data Source.
After instantiating a Command object, the code prepares to generate a couple of DataReaders by opening the cnn1 Connection object. The drd1 DataReader returns data from the master data source, and the drd2 DataReader extracts data from the detail data source. The Console.WriteLine statement for the master data source prints the master data source's first two column values, which are OrderID and OrderDate. The Console.WriteLine statement for the detail data source prints all the rows from the Order Details table with an OrderID matching the value that shows in TextBox1 .Figure 4 shows Form3 immediately after a click to the button labeled Shape. The Output window below the form presents the hierarchical result set. The first line shows the row from the master data source, including the OrderID and OrderDate column values. The next three Rows show the detail line it it itemics for the order with an orderid value of 10248. The second and third columns are forproductid and unitprice column values. Printing the ProductID column value instead of the ProductName column value makes it more difficult to discern the product to which each line item refers. In addition, it's not transparent from the output that UnitPrice column values are currency values.
Return Hierarchical Result Sets with General Tools
The second sample for returning hierarchical data relies on general tools, such as adaptations of those already presented in this article. The detailed code for the second sample appears in the Button2_Click procedure and a related procedure named ComputerArrayIndex in the module for Form3 within the HCVSDataReaders project . This second approach to returning hierarchical data creates three arrays based on associated DataReaders for the Orders, Order Details, and Products tables in the Northwind database. Using arrays in this manner can reduce the load on a database server since it allows an application to close the DataReader and its associated Connection to a data source.The following code segment from Button2_Click in the Form3 module illustrates the approach used to generate the Orders array. The PopArray procedure within Form2 was briefly described earlier. It generates an array based on a DataReader for The Northwind Database. You Pass It a Maximum Number of Rows To Read As Well A s a table name. By the way, the PopArray procedure does close its DataReader after populating the array. The ComputeArrayIndex procedure generates a one-dimensional array, IdxOrders, from the first column of a two-dimensional array, such as Orders.
Dim IntmaxordersRows = 830
ORDERS = Form2.PopArray ("Orders", _
IntMaxordersRows)
IDXORDERS = ComputeArrayIndex (Orders, _
IntMaxordersRows)
The one-dimensional index array can speed the lookup of rows in a two-dimensional array faster than scanning all the rows in the two-dimensional array for a value matching a criterion. This is because Visual Basic .NET offers an IndexOf Shared method for its Array class that returns the index corresponding to a value in a one-dimensional array. The following code sample shows the syntax for using this method with the IdxOrders array to recover OrderID and OrderDate column values from the Orders array. The code segment also formats The OrderDate Column Value To Exclude The Irrelevant Time Portion of The DateTime Value.dim intidx as integer = _
Array.indexof (idxorders, _
Integer.Parse (TextBox1.text))
Console.writeLine ("{0}, {1}", _
Orders (intIDX, 0), _
DateTime.Parse (_
Orders (intIDX, 3)). Tostring ("m / dd / yy"))
Figure 5 shows the final output from the Button2_Click procedure for the OrderID value appearing in Figure 4. Notice that the procedure performs a lookup for the ProductID values and displays ProductName column values in their stead. The lookup logic to recover ProductName column values based on ProductID column values is an extension of the code for looking up LastName column values based on ReportsTo column values from the second sample in this article as well as the preceding code segment. The approach to formatting the UnitPrice as a currency value simply invokes the familiar FormatCurrency function While You Can Use More Robust Means for Formatting Currency Values, It's Nice To Know That Visual Basic .NET Supports The Familiar and easy-to-use formatcurrency function.
ConclusionsDataReaders are fast, flexible, and powerful tools for data access to remote data sources. This article highlights three specific kinds of applications for DataReaders in .NET applications, but there are many others. Exploiting DataReaders in your custom solutions will make them go faster and Even offer you the chance to reinforce you Basic .Net Development Skills. You'll offen becom DataReaders by useing the in concert with arrays.download 407dobson.zip
To Find Out More About Hardcore Visual Studio and Pinnacle Publishing, Visit Their Web Site At http://www.pinpub.com/
Note: this is not a Microsoft Corporation Web Site. Microsoft Is Not Responsible for ITS Content.
This article is reproduced from the July 2004 issue of Hardcore Visual Studio. Copyright 2004, by Pinnacle Publishing, Inc., unless otherwise noted. All rights are reserved. Hardcore Visual Studio is an independently produced publication of Pinnacle Publishing, Inc. No part of this article may be used or reproduced in any fashion (except in brief quotations used in critical articles and reviews) without prior consent of Pinnacle Publishing, Inc. To contact Pinnacle Publishing, Inc., please call 1-800-788-1900.