如何使用SQL将实际值插入表中?

时间:2016-09-26 10:00:57

标签: sql delphi

我尝试使用以下代码将值插入MedicationPrices表。

procedure TForm1.btnAddMedicineClick(Sender: TObject);
var
 sMedication, sQuantity : string;
 rPrice : real;
begin
sMedication := InputBox('Add Medication','Please enter the medications name','');
sQuantity := InputBox('Add Medication','Please enter the the quantity','');
rPrice := StrToFloat(InputBox('Add Medication','Please enter the the price',''));

with dmHospital do
begin
  qryPrices.SQL.Clear;
  qryPrices.SQL.Add('INSERT INTO MedicationPrices (Medication, Quantity)');
  qryPrices.SQL.Add('VALUES(' + QuotedStr(sMedication) +',' + QuotedStr(sQuantity)  + ' )');
  qryPrices.Parameters.ParamByName('Price').Value := rPrice;
  qryPrices.ExecSQL;
  qryPrices.SQL.Clear;
  qryPrices.SQL.Text := 'SELECT * MedicationPrices ';
  qryPrices.Open;
end;
end;

然而,它和一些不同的变化只是不起作用。我明白了: Error message

我不明白为什么它没有看到' Price'因为它显然在表中。 Design view of table

1 个答案:

答案 0 :(得分:9)

您应该在查询中添加参数(与VALUES一致)。

然后,当您使用ParamByName函数时,它将基本上替换参数(:Price)来查询您设置的值(rPrice )。

更正示例:

with dmHospital do
begin
  qryPrices.SQL.Clear;
  qryPrices.SQL.Add('INSERT INTO MedicationPrices (Medication, Quantity, Price)');
  qryPrices.SQL.Add('VALUES(:Medication, :Quantity, :Price)');
  qryPrices.Parameters.ParamByName('Medication').Value := sMedication;
  qryPrices.Parameters.ParamByName('Quantity').Value := sQuantity;
  qryPrices.Parameters.ParamByName('Price').Value := rPrice;
  qryPrices.ExecSQL;
  qryPrices.SQL.Clear;
  qryPrices.SQL.Text := 'SELECT * FROM MedicationPrices ';
  qryPrices.Open;
end;

另请参阅this Q&A关于INSERT中Delphi中的参数。