ADO Tutorial (Visual Basic)

Microsoft ActiveX Data Objects (ADO)

ADO Tutorial (Visual Basic)

This is the ADO tutorial, written in Microsoft Visual Basic. See the ADO Tutorial for a description of the purpose of this tutorial.

Public Sub Main()    ' Tutorial in VB

Dim cnn As New ADODB.Connection
Dim cmd As New ADODB.Command
Dim rst As New ADODB.Recordset

' Step 1 - Open a Connection
cnn.Open "DSN=Pubs;uid=sa;pwd=;"

' Step 2 - Create a Command
Set cmd.ActiveConnection = cnn
cmd.CommandText = "SELECT * from Authors"

' Step 3 - Execute the Command
rst.CursorLocation = adUseClient
rst.Open cmd, , adOpenStatic, adLockBatchOptimistic

' Step 4 - Manipulate the Data
rst!au_lname.Properties("Optimize") = True
rst.Sort = "au_lname"
rst.Filter = "phone LIKE '415 5*'"
rst.MoveFirst
Do While Not rst.EOF
    Debug.Print "Name = "; rst!au_fname; " "; rst!au_lname; _
        ", Phone = "; rst!phone
    rst!phone = "777" & Mid(rst!phone, 4)
    rst.MoveNext
Loop

rst.Filter = adFilterNone

' Step 5 - Update the Data
cnn.BeginTrans
On Error GoTo ConflictHandler
rst.UpdateBatch

'Step 6, part A - Conclude the Update (Accept changes)
cnn.CommitTrans

ExitTutorial:
On Error GoTo 0
rst.Close
cnn.Close
Exit Sub

'Step 6, part B - Conclude the Update (Reject changes)
ConflictHandler:
rst.Filter = adFilterConflictingRecords
rst.MoveFirst
Do While Not rst.EOF
    Debug.Print "Conflict: Name =  "; rst!au_fname; " "; rst!au_lname
    rst.MoveNext
Loop
cnn.RollbackTrans
Resume ExitTutorial

End Sub

This is the end of the Visual Basic tutorial.