2016-09-26 73 views
-4

我想用下面的代碼將值插入到MedicationPrices表中。如何使用SQL將實數值插入到表中?

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

我不明白爲什麼它沒有看到'價格',因爲它清楚地在表格中。 Design view of table

+1

我想你錯過了列(又名字段)名稱和查詢參數之間的區別。它們不是同一件事。 – MartynA

+2

我不願意在這家醫院找到自己: -/ –

+1

with..do應該永遠被禁止imo –

回答

9

您應該在查詢中添加參數(帶有VALUES的行)。

然後,當你使用ParamByName功能,它基本上會通過您設置的值(rPrice)取代從查詢參數(:Price)。校正的

實施例:

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大約在Delphi參數在INSERT。

+1

看起來SELECT語句中存在FROM缺失。 – MartynA

+1

很好的@MartynA,我沒有檢查代碼的其餘部分。我剛剛編輯我的答案;-) – brclz

+0

@brclz感謝您的回答,但我仍然得到相同的錯誤信息,但與':藥物',而不是。 –

相關問題