具名命令
建立及執行簡單命令會顯示執行命令的其中一種方式。 有另一種方式:您可以將其設定為具名命令,然後直接在 Connection 物件上呼叫此具名命令 (指派給 Command 物件的 ActiveConnection 屬性)。 命名命令表示將名稱指派給 Command 物件的 Name 屬性。 例如,
objCmd.Name = "GetCustomers"
objCmd.ActiveConnection = objConn
objConn.GetCustomers objRs
具名命令的作用就像是 Connection 物件的「自訂方法」一樣。 命令結果會以此「自訂方法」的 out 參數形式傳回。
下列範例將示範此功能。
'BeginNamedCmd
On Error GoTo ErrHandler:
Dim objConn As New ADODB.Connection
Dim objCmd As New ADODB.Command
Dim objRs As New ADODB.Recordset
' Connect to the data source.
Set objConn = GetNewConnection
objCmd.CommandText = "SELECT CustomerID, CompanyName FROM Customers"
objCmd.CommandType = adCmdText
'Name the command.
objCmd.Name = "GetCustomers"
objCmd.ActiveConnection = objConn
' Execute using Command.Name from the Connection.
objConn.GetCustomers objRs
' Display.
Do While Not objRs.EOF
Debug.Print objRs(0) & vbTab & objRs(1)
objRs.MoveNext
Loop
'clean up
objRs.Close
objConn.Close
Set objRs = Nothing
Set objConn = Nothing
Set objCmd = Nothing
Exit Sub
ErrHandler:
'clean up
If objRs.State = adStateOpen Then
objRs.Close
End If
If objConn.State = adStateOpen Then
objConn.Close
End If
Set objRs = Nothing
Set objConn = Nothing
Set objCmd = Nothing
If Err <> 0 Then
MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
'EndNamedCmd