具名命令
建立和執行簡單命令 會顯示執行命令的一種方式。 還有另一種方式:您可以將它設為具名命令,然後在 Connection 物件上直接呼叫這個具名命令(指派給 Command 物件的 ActiveConnection 屬性)。 命名命令表示將名稱指派給 Command 物件的 Name 屬性。 例如
objCmd.Name = "GetCustomers"
objCmd.ActiveConnection = objConn
objConn.GetCustomers objRs
具名命令的作用就像是 Connection 物件上的「自定義方法」一樣。 命令的結果會以這個 「custom method」 的 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