將參數傳遞至具名命令
就像命令的結果以具名命令的 傳出 變數一樣,參數化命令的參數可以當作 變數中的 傳入具名命令。
下列程式代碼範例會嘗試從 Northwind 資料庫擷取其 CustomerID 為 “ALKFI” 的客戶所下的所有訂單。 呼叫具名命令時,會提供 CustomerID 的值。
Const DS = "MySqlServer"
Const DB = "Northwind"
Const DP = "SQLOLEDB"
Dim objConn As New ADODB.Connection
Dim objRs As New ADODB.Recordset
Dim objComm As New ADODB.Command
CommandText = "SELECT OrderID, OrderDate, " & _
"RequiredDate, ShippedDate " & _
"FROM Orders " & _
"WHERE CustomerID = ? " & _
"ORDER BY OrderID"
ConnectionString = "Provider=" & DP & _
";Data Source=" & DS & _
";Initial Catalog=" & DB & _
";Integrated Security=SSPI;"
' Connect to the data source.
objConn.Open ConnectionString
' Set a named command.
objComm.CommandText = CommandText
objComm.CommandType = adCmdText
objComm.Name = "GetOrdersOf"
Set objComm.ActiveConnection = objConn
' Call the named command, passing a CustomerID value
' as the input parameter.
' "ALFKI" is the required input parameter,
' objRs is the resultant output variable.
objConn.GetOrdersOf "ALKFI", objRs
' Display the result.
Debug.Print "All orders by ALFKI:"
Do While Not objRs.EOF
Debug.Print vbTab & objRs(0) & vbTab & objRs(1) & vbTab & _
objRs(2) & vbTab & objRs(3)
objRs.MoveNext
Loop
' Clean up.
objRs.Close
objConn.Close
Set objRs = Nothing
Set objConn = Nothing
Set objComm = Nothing
請注意,所有輸入參數都必須在任何輸出變數之前,而且參數的數據類型必須相符或可以轉換成對應字段的數據類型。 下列語句-
objConn.GetOrdersOf 12345, objRs
-將會導致數據類型不相符的錯誤,因為必要的輸入參數是 String 類型,而不是 Integer 類型。
接下來的呼叫 -
objConn.GetOrdersOf "12345", objRs
-是有效的,但會產生空的結果集,因為資料庫中沒有這類記錄。