Chapter 8: Developing Database Applications with ADO 279 'Check object for nothing If cn = "" Then MsgBox "No connection information has been entered" End Else cn.Open cn.Close End If dl = Nothing End Sub In the beginning of this listing, you can see where an instance of an existing ADO Connection object is passed into the subroutine as a parameter. This ADO Connection object is set to an instance of the Connection object that will be returned by the Data Link object. The following Dim statement then creates a new instance of the DataLinks object named dl. After the dl DataLinks object has been instantiated, you can then use the Data Link object’s PromptNew method to display the Data Link dialog box, as shown in Figure 8-9. Figure 8-9 Selecting the OLE DB Provider using the Data Link dialog box 280 Microsoft SQL Server 2005 Developer’s Guide When the PromptNew method is executed, the Data Link dialog box initially displays the Provider tab that lists all the OLE DB providers that are installed on the system. The Data Link dialog box lets you both configure and connect to a target data source. To connect to SQL Server using the Data Link dialog box, the user must first select the OLE DB provider to be used from the list of the OLE DB providers displayed on the Provider tab. In Figure 8-9, you can see the OLE DB Provider for SQL Server has been selected. Clicking the Next button or selecting the Connection tab displays the OLE DB Connection information dialog box, as shown in Figure 8-10. The Connection tab lets the user select the name of the SQL Server system that will be connected to, as well as enter authentication information and specify a default database. In Figure 8-10, you can see the Data Link dialog box is being used to connect to a system named teca-sql2005, that Integrated Security will be used, and AdventureWorks will be set as the default database. When all the connection information has been entered, clicking OK returns the connection information to the application. Figure 8-10 Providing the OLE DB Connection information on the Data Link dialog box Chapter 8: Developing Database Applications with ADO 281 To connect to SQL Server, the Data Links object contains its own ADO Connection object. An instance of that Connection object is returned by the PromptNew method. The previous listing shows the Connection object returned by the dl object’s PromptNew method being assigned to the ADO Connection object named cn. If the user clicks Cancel in the dialog box, however, then no Connection object is returned. Enabling VB’s error handler allows the properties of the cn Connection object to be tested without generating a run-time error. The cn Connection object is checked to see if it contains a value. If the Connection object is equal to nothing, then the user clicked the Cancel button. The message is displayed and the program is ended using the End function. Otherwise, the cn Connection object’s Open method is executed to establish a session with the SQL Server system identified in the Data Link dialog box. Then all the system resources used by the dl DataLinks object are released when the object is set to nothing before the subroutine is exited. Ending a Connection As the previous examples illustrate, before ending your application, you should use the Connection object’s Close method to end the database connection. An example of the Close method follows: Dim cn As New ADODB.Connection 'Perform work with the connect and then end it cn.Close Retrieving Data with the ADO Recordset ADO lets you retrieve data using either the Recordset or the Command object. Both of these objects can be used with an active Connection object or can open their own connections. In the following section, you see how to retrieve data from SQL Server using the Recordset object. You learn about the differences between the various types of ADO Recordset objects, as well as how to traverse Recordset objects and work with column values using the ADO Fields collection. ADO Recordset Types Like the Recordset object found in DAO or RDO’s Resultset object, the ADO Recordset object represents a result set that’s returned from a database query. ADO Recordset objects support several different types of cursors that correspond to the different types of ODBC cursors. ADO provides support for forward-only, static, keyset, and dynamic Recordset objects. The type of cursor used in an ADO 282 Microsoft SQL Server 2005 Developer’s Guide Recordset object must be set before the Recordset is opened. If you don’t specify the type of Recordset object you want to use, ADO automatically uses a forward-only cursor. Forward-Only Cursors As a default, ADO uses a forward-only cursor. The forward- only cursor provides the best performance and the least overhead of any of the ADO cursor types; however, it’s also less capable than other ADO cursors. ADO Recordset objects that use forward-only cursors are updatable, but you can modify only the current row. Any changes in the base table that other users make aren’t reflected in the Recordset object. Static Cursors A static cursor provides a snapshot of the data at the time the cursor was opened. ADO Recordset objects that use static cursors aren’t updatable, and they don’t reflect any changes made in the base tables unless the cursor is closed and reopened. Because of their static nature, Recordset objects created by static cursors are generally less resource-intensive than Recordset objects that use keyset or dynamic cursors. Because the static cursor makes a local copy of the data, however, you need to be careful about using this type of cursor with large result sets. Using a static cursor with an extremely large result set can definitely be a bigger resource drain than either a keyset or a dynamic cursor. Keyset Cursors Keyset cursors build a local set of keys where each key is an index to a row in the result set. When your application accesses a Recordset object that uses a keyset cursor, the key value from the local keyset retrieves the corresponding row from the base table. Recordset objects that use keyset cursors are updatable, but after they are fully populated, they don’t dynamically reflect changes other users make in the base table. Keyset cursors are capable, but they are also relatively resource- intensive. This is because the client system must maintain the keys for the entire result set, as well as a buffer that contains a block of the actual data values. Dynamic Cursors Dynamic cursors are the most powerful and capable type of ADO cursors, but they are also the most resource-intensive. Dynamic cursors are similar to keyset cursors. Both use a local set of keys that correspond to each row in the result set, and both are fully updatable. However, unlike Recordset objects that use a keyset cursor, Recordset objects that use dynamic cursors can reflect any changes automatically that other applications make to the base tables. To maintain the result set dynamically, ADO Recordset objects that use dynamic cursors must refresh the result set each time a new fetch operation is performed, automatically updating the local result set with any changes. Chapter 8: Developing Database Applications with ADO 283 Using a Forward-Only Recordset Object The ADO Recordset object can be used with an existing Connection object, or it can optionally open a connection to the target data source on its own. TIP When an ADO Recordset object opens its own Connection object, the ADO object framework automatically creates a Connection object, but that object isn’t associated with a Visual Basic program variable. This makes using the Recordset object quick and easy, but it also adds the overhead required to create the Connection object for each new Recordset object. If your application needs to create multiple Recordset objects that use the same database, it’s much more efficient to use a Connection object and then associate each new Recordset object with the existing Connection object. The following code listing illustrates how to use a Recordset object with an ADO Connection object: Private Sub ForwardOnlyRecordset(cn As ADODB.Connection) Dim rs As New ADODB.Recordset ' Associate the Recordset with the open connection object rs.ActiveConnection = cn 'Use the open method rs.Open "Select * From Sales.SalesPerson", , , , adCmdText 'Display the results in a grid DisplayForwardGrid rs, hflxResults 'Close the recordset & release its resources rs.Close Set rs = Nothing End Sub Before using the ADO Recordset object, you need to assign it to a Visual Basic variable. The Dim statement at the beginning of this subroutine creates a new ADO Recordset object named rs. Next, the ActiveConnection property of the rs Recordset object is set to the active Connection object named cn, which was passed into this subroutine as a parameter. Assigning the rs object’s ActiveConnection property to an active Connection object associates the new Recordset object with the connected SQL Server system. The Connection object must have been previously instantiated 284 Microsoft SQL Server 2005 Developer’s Guide and connected to SQL Server, using one of the connection methods illustrated in the prior Connection object examples. The ADO Connection object could use either the OLE DB Provider for ODBC or the OLE DB Provider for SQL Server. All the subsequent ADO coding for both OLE DB providers is the same. After the ActiveConnection property is set, a forward-only cursor is opened using the Recordset object’s Open method. The Recordset object’s Open method takes five optional parameters. The first parameter is a Variant data type, and as you might think, it can accept a number of different values, such as the name of an existing Command object, a SQL statement, a table name, or the name of a stored procedure. In the preceding example, the first parameter contains a simple SQL Select statement that creates a result set consisting of all the rows and columns contained in the Sales.SalesPerson table that’s found in the AdventureWorks database. The Open method’s optional second parameter can be used to associate the Recordset object with an ADO Connection object. This parameter performs exactly the same function as the Recordset object’s ActiveConnection property, and you can use this parameter as an alternative to setting the ActiveConnection property. This parameter can accept either a string that contains an OLE DB connection string or a variant that contains the name of an active ADO Connection object. If you specify an OLE DB connection string rather than the name of a Connection object, then ADO implicitly creates a Connection object and uses it to establish a link to the target data source. The third optional parameter of the Open method specifies the cursor type the Recordset object is to use. If this parameter isn’t designated, then the cursor type is set to forward-only by default, which is the simplest and also the best-performing option. Table 8-5 presents the ADO constants used to specify the cursor type an ADO Recordset object will use. The fourth optional parameter specifies the type of locking the OLE DB provider is to use. If this parameter isn’t designated, then the lock type will be set to read-only by default. Table 8-6 presents the ADO constants used to specify the lock type an ADO Recordset object is to use. ADO Constant Cursor Type adOpenForwardOnly Forward-only cursor (default) adOpenStatic Static cursor adOpenKeyset Keyset cursor adOpenDynamic Dynamic cursor Table 8-5 ADO Recordset Cursor Types Chapter 8: Developing Database Applications with ADO 285 The fifth optional parameter specifies the options of the Open method. The options parameter explicitly tells ADO how to handle the first parameter if the first parameter doesn’t contain the name of an ADO Command object. TIP While this may seem a bit innocuous, specifying a value for the fifth parameter can result in improved performance because ADO doesn’t need to test the data source to determine what type of value was supplied in the first parameter of the Open method. If you specify a constant for the fifth parameter that doesn’t match the value supplied in the first parameter, however, then ADO generates an error. Table 8-7 presents the ADO constants used to specify the options to be used by an ADO Recordset object. After the Open method completes, the data in the Recordset object is available for processing. In the previous example, the DisplayForwardGrid subroutine is called to display the contents of the rs Recordset object in a grid. In the next section of code, you see how to move through the rows in the Recordset object, as well as how to Lock Type Description AdLockReadOnly Read-only (default) AdLockPessimistic Pessimistic locking AdLockOptimistic Optimistic locking AdLockBatchOptimistic Optimistic locking using batch mode updates Table 8-6 ADO Recordset Lock Types Option Description adCmdUnknown The source is unknown and ADO must test for it (default). adCmdFile The source is the name of a file. adCmdStoredProc The source is the name of a stored procedure. adCmdTable The source is the name of a table. adCmdText The source is a command (or SQL statement). Table 8-7 Recordset Source Options 286 Microsoft SQL Server 2005 Developer’s Guide access the column information in the Fields collection. The DisplayForwardGrid subroutine is shown here: Private Sub DisplayForwardGrid _ (rs As ADODB.Recordset, hflxResults As MSHFlexGrid) Dim fld As ADODB.Field ' Setup the hflxResults hflxResults.Redraw = False hflxResults.FixedCols = 0 hflxResults.FixedRows = 0 hflxResults.Cols = rs.Fields.Count hflxResults.Rows = 1 hflxResults.Row = 0 hflxResults.Col = 0 hflxResults.Clear 'Setup the hflxResults headings For Each fld In rs.Fields hflxResults.Text = fld.Name hflxResults.ColAlignment(hflxResults.Col) = 1 hflxResults.ColWidth(hflxResults.Col) = _ Me.TextWidth(fld.Name & "AA") If hflxResults.Col < rs.Fields.Count - 1 Then hflxResults.Col = hflxResults.Col + 1 End If Next fld ' Move through each row in the record set Do Until rs.EOF ' Set the position in the hflxResults hflxResults.Rows = hflxResults.Rows + 1 hflxResults.Row = hflxResults.Row + 1 hflxResults.Col = 0 'Loop through all fields For Each fld In rs.Fields hflxResults.Text = fld.Value If hflxResults.ColWidth(hflxResults.Col) < _ Me.TextWidth(fld.Value & "AA") Then hflxResults.ColWidth(hflxResults.Col) = _ Me.TextWidth(fld.Value & "AA") End If Chapter 8: Developing Database Applications with ADO 287 If hflxResults.Col < rs.Fields.Count - 1 Then hflxResults.Col = hflxResults.Col + 1 End If Next fld rs.MoveNext Loop If hflxResults.Rows = 1 Then hflxResults.Rows = 2 End If hflxResults.FixedRows = 1 hflxResults.Redraw = True End Sub At the beginning of this subroutine, you can see where an instance of the ADO Recordset object named rs is passed as the first parameter and an instance of the MSHFlexGrid object is passed as the second parameter of the DisplayForwardGrid subroutine. This allows the same subroutine to be reused with many different Recordset and Grid objects. The Dim statement in this subroutine creates an instance of an ADO Field object named fld. NOTE Unlike the previous ADO examples, there’s no need to use the New keyword to declare either the ADO Recordset object or the ADO Field object. This was because both of these variables are references to instances of the Recordset and Field objects that were already created and, subsequently, passed in to this subroutine. After the ADO objects have been declared, the next portion of the DisplayForwardGrid subroutine sets up the grid to display the contents of the ADO Recordset object. First the grid’s Redraw property is set to False to improve performance and prevent flicker while data is being added to the grid. Next, setting each property to 0 clears any existing FixedCols and FixedRows settings. Then the number of grid columns is set using the Count property of the Recordset objects Fields collection. Each column in the result set is represented by a Field object, and all the Field objects are contained in the Recordset object’s Fields collection. Retrieving the Fields collection’s Count property allows the grid to be displayed using one grid column per result set column. Next, the grid’s Rows property is set up to have at least one row that will contain the column heading information. Then the grid’s Row and Col properties are used to set the current grid cell at row 0 column 0 288 Microsoft SQL Server 2005 Developer’s Guide (the upper left-hand corner of the grid) and the grid’s Clear method is executed to ensure no unwanted data is in the grid. Once the initial preparation of the grid object is completed, the heading values and sizes for each of the grid’s columns are set up. Every column in the result set has a corresponding Field object in the Recordset object’s Fields collection. A For Each loop iterates through all the Field objects contained in the Fields collection. The first action within the For Each loop sets the current row to the first row in the grid. Then the Field object’s Name property is used as heading text for the grid columns. Next, the grid’s ColAlignment property for each column is set to left-align the cell text by setting the ColAlignment property to 1. To set the alignment of the current column, the ColAlignment property requires the index of the current grid column. In this case, the index is supplied using the hflxResults.Col property. Next, the column width of each column in the grid is set using the grid’s ColWidth property. The ColWidth property must be assigned a value in twips (one twentieth of a printer’s point); Visual Basic’s TextWidth function is used to return the number of twips required to display the name of each Field object. The correct number of twips is determined by creating a placeholder string using the Field object’s Name property (which contains the name of the column), plus two extra characters (AA) that help to prevent the grid columns from appearing too crowded. Finally, the current column is incremented by adding 1 to the value of the grid’s current Col property. NOTE Because the ADO object framework doesn’t provide an OrdinalPosition property like the DAO and RDO frameworks, you must either add additional code to track the current column position manually or use the value of the Field object’s index in the Fields collection. Next, a Do Until loop reads through all the columns in the Recordset object. The Do Until loop continues until the Recordset’s EOF (End of File) property becomes true—which indicates all the rows in the Recordset have been read. Inside the Do Until loop, the grid’s Rows property is incremented to expand the size of the grid for each row read from the Recordset, and the Row property is incremented to move the current position to the new grid row. Then the current grid column is set to 0, which is the first column, and a For Each loop is used to move the data values contained in the Fields collection to the grid columns. An If test ensures the code doesn’t attempt to access an invalid grid column. After all the Field values have been processed, the Recordset object’s MoveNext method moves the cursor to the next row in the Recordset object. You can see the contents of the ADO Recordset displayed in Figure 8-11. . with the connected SQL Server system. The Connection object must have been previously instantiated 284 Microsoft SQL Server 2005 Developer’s Guide and connected to SQL Server, using one of. name of a table. adCmdText The source is a command (or SQL statement). Table 8-7 Recordset Source Options 286 Microsoft SQL Server 2005 Developer’s Guide access the column information in the. Figure 8-9. Figure 8-9 Selecting the OLE DB Provider using the Data Link dialog box 280 Microsoft SQL Server 2005 Developer’s Guide When the PromptNew method is executed, the Data Link dialog box initially