Delete records using TFDQuery in Delphi

Issue

Help me to fix this problem to delete records with TFDQuery.

When this value of record is choosed by me with Edit.Text or DBEdit.Text, I try like this but it is not working:

FDQuery.SQL.Text := 'delete * FROM MyTable column_name =:KEY1 ';
FDQuery.ParamByName('KEY1').AsString = 'dbedit.text';
FDQuery.Open;

Solution

  fdquery.SQL.Text := 'DELETE FROM MyTable WHERE column_name = :KEY1';
  fdquery.ParamByName('KEY1').AsString := dbedit.Text;
  fdquery.Execute();

You could also use TFDCommand rather than TFDQuery as you are not expecting to read the result:

  fdcommand.CommandText := 'DELETE FROM MyTable WHERE column_name = :KEY1';
  fdcommand.ParamByName('KEY1').AsString := dbedit.Text;
  fdcommand.Execute();

If this is a command you expect to re-use you could put the SQL statement into the command at design time, with the parameter name, and then at run time you would only need to do:

  fdcommand.ParamByName('KEY1').AsString := dbedit.Text;
  fdcommand.Execute();

Depending on the underlying database you are using have commands pre-populated can allow the query to be prepared in advance. For complex queries (unlike this one) this means that the execution plan is built only once.

Answered By – Rob Lambden

Answer Checked By – Robin (AngularFixing Admin)

Leave a Reply

Your email address will not be published.