Public Sub ExecuteX() Dim strsqlChange As String Dim strsqlRestore As String Dim strCnn As String Dim cnn1 As ADODB.Connection Dim cmdChange As ADODB.Command Dim rstTitles As ADODB.Recordset Dim errLoop As ADODB.Error ' 定义两个 sql 语句作为命令文本执行。 strsqlChange = 'UPDATE Titles SET Type = ' & _ ''self_help' WHERE Type = 'psychology'' strsqlRestore = 'UPDATE Titles SET Type = ' & _ ''psychology' WHERE Type = 'self_help'' ' 打开连接。 strCnn = 'Provider=sqloledb;' & _ 'Data Source=srv;Initial Catalog=pubs;User Id=sa;Password=; ' Set cnn1 = New ADODB.Connection cnn1.Open strCnn ' 创建命令对象。 Set cmdChange = New ADODB.Command Set cmdChange.ActiveConnection = cnn1 cmdChange.CommandText = strsqlChange ' 打开标题表。 Set rstTitles = New ADODB.Recordset rstTitles.Open 'titles',cnn1,adCmdTable ' 打印原始数据报告。 Debug.Print _ 'Data in Titles table before executing the query' PrintOutput rstTitles ' 清除 Errors 集合的外部错误。 cnn1.Errors.Clear ' 调用 ExecuteCommand 子例程执行 cmdChange 命令。 ExecuteCommand cmdChange,rstTitles ' 打印新数据报告。 Debug.Print _ 'Data in Titles table after executing the query' PrintOutput rstTitles ' 使用 Connection 对象的 execute 方法执行 sql 语句以恢复数据。 ' 捕获错误,必要时检查 Errors 集合。 On Error GoTo Err_Execute cnn1.Execute strsqlRestore,adExecuteNoRecords On Error GoTo 0 ' 通过再查询记录集检索当前数据。 rstTitles.Requery ' 打印已恢复数据的报告。 Debug.Print 'Data after executing the query ' & _ 'to restore the original information' PrintOutput rstTitles rstTitles.Close cnn1.Close Exit Sub Err_Execute: ' 将任何由执行查询引起的错误通知用户。 If Errors.Count > 0 Then For Each errLoop In Errors MsgBox 'Error number: ' & errLoop.Number & vbCr & _ errLoop.Description Next errLoop End If Resume Next End Sub Public Sub ExecuteCommand(cmdTemp As ADODB.Command,_ rstTemp As ADODB.Recordset) Dim errLoop As Error ' 运行指定的 Command 对象。捕获错误,必要时检查 Errors 集合。 On Error GoTo Err_Execute cmdTemp.Execute On Error GoTo 0 '通过再查询记录集检索当前数据。 rstTemp.Requery Exit Sub Err_Execute: ' 将任何由执行查询引起的错误通知用户。 If Errors.Count > 0 Then For Each errLoop In Errors MsgBox 'Error number: ' & errLoop.Number & vbCr & _ errLoop.Description Next errLoop End If Resume Next End Sub Public Sub PrintOutput(rstTemp As ADODB.Recordset) ' 枚举 Recordset。 Do While Not rstTemp.EOF Debug.Print ' ' & rstTemp!Title & _ ',' & rstTemp!Type rstTemp.MoveNext Loop End Sub |
|