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

Oce*_*ght -4 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;
Run Code Online (Sandbox Code Playgroud)

然而,它和一些不同的变化只是不起作用.我明白了: 错误信息

我不明白为什么它没有看到"价格",因为它显然在表中. 表设计视图

brc*_*clz 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;
Run Code Online (Sandbox Code Playgroud)

另请参阅INSERT中有关Delphi中参数的问答.

  • @OceanKnight:是的!语法有点不对,它的`ParamByName('PARAMETER_NAME').值没有两个点.我更新了它. (2认同)