Search code examples
delphiadodelphi-xe5

Insert data by TADOCommand in Delphi


I have a table with four fields, one of those fields is the primary key. When I run the following commands:

var
  iAffectedRows: integer;
begin
  ADOCommand1.CommandText := 'insert into table_1(Field_1, Field_2, Field_3)   values(:A_Field_1, :A_Field_2, :A_Field_3)';      

  ADOCommand1.Parameters.FindParam('A_Field_1').Value := '100';
  ADOCommand1.Parameters.FindParam('A_Field_2').Value := '200';
  ADOCommand1.Parameters.FindParam('A_Field_3').Value := '300';

  ADOCommand1.Execute(iAffectedRows);
end;

The result is :

enter image description here

The Field_1 value is 0.

(This result is due to run the command : ADOCommand1.Execute(iAffectedRows))

But with this command everything is correct :ADOCommand1.Execute()

Is there a solution to this problem?


Solution

  • It seems you already have the solution - call the no-argument version of Execute().

    function Execute: _Recordset;
    

    You are calling the 1-argument version of Execute(), which does not output the number of rows affected:

    function Execute(const Parameters: OleVariant): _Recordset;
    

    By passing iAffectedRows to this version, you are replacing the first parameter value with whatever value iAffectedRows initially contains, which just happens to be 0.

    If you want to receive the number of rows affected, you need to use the 2-argument version of Execute() instead:

    function Execute(var RecordsAffected: Integer; const Parameters: OleVariant): _Recordset;
    

    For example:

    var
      iAffectedRows: integer;
    begin
      ADOCommand1.CommandText := 'insert into table_1(Field_1, Field_2, Field_3) values(:A_Field_1, :A_Field_2, :A_Field_3)';
    
      ADOCommand1.Parameters.FindParam('A_Field_1').Value := '100';
      ADOCommand1.Parameters.FindParam('A_Field_2').Value := '200';
      ADOCommand1.Parameters.FindParam('A_Field_3').Value := '300';
    
      ADOCommand1.Execute(iAffectedRows, EmptyParam);
    end;
    

    Or:

    var
      iAffectedRows: integer;
    begin
      ADOCommand1.CommandText := 'insert into table_1(Field_1, Field_2, Field_3) values(:A_Field_1, :A_Field_2, :A_Field_3)';    
      ADOCommand1.Execute(iAffectedRows, VarArrayOf('100', '200', '300'));
    end;