適用先: Access 2013、Office 2013
次の例では 、Command オブジェクトのより興味深い使用方法を示します。この例では、SQL コマンドのテキストが変更され、パラメーター化されています。 これにより、コマンドを再利用し、毎回パラメーターに異なる値を渡すことができます。 Command オブジェクトの Prepared プロパティが True に設定されているため、ADO では、初めて実行する前に CommandText で指定されたコマンドをコンパイルするプロバイダーが必要です。 また、コンパイルされたコマンドもメモリに保持されます。 これにより、コマンドの準備に必要なオーバーヘッドが原因で、最初の実行時にコマンドの実行が少し遅くなりますが、その後コマンドが呼び出されるたびにパフォーマンスが向上します。 したがって、コマンドは、複数回使用される場合にのみ準備する必要があります。
'BeginManualParamCmd
On Error GoTo ErrHandler:
Dim objConn As New ADODB.Connection
Dim objCmd As New ADODB.Command
Dim objParm1 As New ADODB.Parameter
Dim objRs As New ADODB.Recordset
' Set the CommandText as a parameterized SQL query.
objCmd.CommandText = "SELECT OrderID, OrderDate, " & _
"RequiredDate, ShippedDate " & _
"FROM Orders " & _
"WHERE CustomerID = ? " & _
"ORDER BY OrderID"
objCmd.CommandType = adCmdText
' Prepare command since we will be executing it more than once.
objCmd.Prepared = True
' Create new parameter for CustomerID. Initial value is ALFKI.
Set objParm1 = objCmd.CreateParameter("CustId", adChar, _
adParamInput, 5, "ALFKI")
objCmd.Parameters.Append objParm1
' Connect to the data source.
Set objConn = GetNewConnection
objCmd.ActiveConnection = objConn
' Execute once and display...
Set objRs = objCmd.Execute
Debug.Print objParm1.Value
Do While Not objRs.EOF
Debug.Print vbTab & objRs(0) & vbTab & objRs(1) & vbTab & _
objRs(2) & vbTab & objRs(3)
objRs.MoveNext
Loop
' ...then set new param value, re-execute command, and display.
objCmd("CustId") = "CACTU"
Set objRs = objCmd.Execute
Debug.Print objParm1.Value
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 objCmd = Nothing
Set objParm1 = 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
Set objParm1 = Nothing
If Err <> 0 Then
MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
'EndManualParamCmd
すべてのプロバイダーが準備されたコマンドをサポートしているわけではありません。 プロバイダーがコマンドの準備をサポートしていない場合は、このプロパティが True に設定されると、すぐにエラーが返される場合があります。 エラーが返されない場合は、コマンドの準備要求が無視され、 Prepared プロパティが False に設定されます。