Tài liệu Using the Connection Object - Pdf 87

Using the Connection Object
As with ADO.NET, you will be using the Connection object to set up a connection to the
database of your choice.
As you get started looking at the different examples, take a look at the main form that
will be used to launch each of them, shown in Figure A.3.
Figure A.3. This form, called frmMain, is the Main form that is used for the
examples in this Appendix.

The button that is used for this example is called btnOpenConn, and the following is the
code used for the Click event, shown here in Listing A.1.
Listing A.1 frmMain.vb: Code for Calling the Routine to Open and Display the
ADO Connection
Private Sub btnOpenConn_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnOpenConn.Click

OpenAndDisplayADOConnection(Me.txtCurrentResults)

End Sub
Each of the buttons calls examples, passing the text box called txtCurrentResults. This
text box is located at the bottom of the form. For clarity, the examples have been grouped
in modules by section. In this case, the first example routine, called
OpenAndDisplayADOConnection, can be found in basConnectionExamples.vb. The
code for this routine is shown in Listing A.2.
Listing A.2 basConnectionExamples.vb: Code for Opening and Displaying the ADO
Connection
Sub OpenAndDisplayADOConnection(ByVal txtResults As TextBox)

Dim cnnNet As New ADODB.Connection()
Dim strConnect As String = _
"Provider=SQLOLEDB.1;Integrated Security=SSPI;" &
"Persist Security Info=False;Initial Catalog=Northwind;Data Source=(local)"


txtResults.Text = cnnNet.ConnectionString

End Sub

Sub OpenNorthwindADOConnection(ByRef cnnCurr As ADODB.Connection)

Dim strConnect As String = "Provider=SQLOLEDB.1;Integrated Security=SSPI;"
& "Persist Security Info=False;Initial Catalog=Northwind;Data
Source=(local)"

Try
cnnCurr.Open(strConnect)

Catch expADO As Exception
MessageBox.Show("The following error occurred: " & expADO.Message)

End Try

End Sub
In the last routine, you can also see how to use the Try…Catch…End Try block to trap
any exceptions that might occur. Next you will see how to use the Connection object with
the Recordset object in VB .NET.


Nhờ tải bản gốc
Music ♫

Copyright: Tài liệu đại học © DMCA.com Protection Status