Handling Command Parameters

From RAD Studio
Jump to: navigation, search

Go Up to Using Command Objects


There are two ways in which a TADOCommand object may use parameters:

  • The CommandText property can specify a query that includes parameters. Working with parameterized queries in TADOCommand works like using a parameterized query in an ADO dataset.
  • The CommandText property can specify a stored procedure that uses parameters. Stored procedure parameters work much the same using TADOCommand as with an ADO dataset.

There are two ways to supply parameter values when working with TADOCommand: you can supply them when you call the Execute method, or you can specify them ahead of time using the Parameters property.

The Execute method is overloaded to include versions that take a set of parameter values as a Variant array. This is useful when you want to supply parameter values quickly without the overhead of setting up the Parameters property:

ADOCommand1.Execute(VarArrayOf([Edit1.Text, Date]));
Variant Values[2];
Values[0] = Edit1->Text;
Values[1] = Date();
ADOCommand1.Execute(VarArrayOf(Values,1));

When working with stored procedures that return output parameters, you must use the Parameters property instead. Even if you do not need to read output parameters, you may prefer to use the Parameters property, which lets you supply parameters at design time and lets you work with TADOCommand properties in the same way you work with the parameters on datasets.

When you set the CommandText property, the Parameters property is automatically updated to reflect the parameters in the query or those used by the stored procedure. At design-time, you can use the Parameter Editor to access parameters, by clicking the ellipsis button for the Parameters property in the Object Inspector. At runtime, use properties and methods of TParameter to set (or get) the values of each parameter.

with ADOCommand1 do begin
  CommandText := 'INSERT INTO Talley ' +
    '(Counter) ' +
    'VALUES (:NewValueParam)';
  CommandType := cmdText;
  Parameters.ParamByName("NewValueParam").Value := 57;
  Execute
end;
ADOCommand1->CommandText = "INSERT INTO Talley ";
ADOCommand1->CommandText += "(Counter) ";
ADOCommand1->CommandText += "VALUES (:NewValueParam)";
ADOCommand1->CommandType = cmdText;
ADOCommand1->Parameters->ParamByName("NewValueParam")->Value = 57;
ADOCommand1->Execute()

See Also