有什么理由不适用? SQL不会向数据库添加记录

时间:2015-10-09 13:22:16

标签: delphi delphi-7

所以我有另一个问题让我心烦意乱,为什么它不起作用,但你们都比我聪明......

代码应该向我的数据库添加新记录,它是一个预算程序,它询问用户他们收到的收入日期,用户的ID,收入的名称和类别以及收到的金额,我使用SQL将其添加到ms访问数据库中。看看,请帮忙!

以下是代码:

procedure TForm1.BitBtn8Click(Sender: TObject);
var
 iNameOfIncome, iCategory, iDate :integer;
 sDate, sAmount :string;
 dDate :TDate;
begin
 with dmRecords do
  begin
   sAmount := Edit7.Text;
   iNameOfIncome := ComboBox10.ItemIndex + 1;
   iCategory := ComboBox2.ItemIndex + 1;
   dDate := DateTimePicker1.Date;
   sDate := DateToStr(dDate);

   qryRecords.SQL.Clear;
   qryRecords.Active := False;
   qryRecords.SQL.Add('INSERT INTO [Income (Ledger)](DateofIncome, [User ID], [Income ID], [Category ID], [Income Amount]');
   qryRecords.SQL.Add('VALUES (' + sDate + ',' + IntToStr(SpinEdit2.Value) + ',' + IntToStr(iNameOfIncome) + ',' + IntToStr(iCategory) + ',' + sAmount + ')');
   qryRecords.ExecSQL;
   qryRecords.SQL.Clear;
   qryRecords.SQL.Add('SELECT * FROM [Income (Ledger)] ORDER BY IncomeNo');
   qryRecords.Active := True;
  end;  

提前谢谢!

1 个答案:

答案 0 :(得分:1)

我认为你应该像这样重写它

  qryRecords.Close;
  qryRecords.SQL.Text :=
  'INSERT INTO [Income (Ledger)](DateofIncome, [User ID], [Income ID], [Category ID], [Income Amount]) ' +
  'VALUES (:DateofIncome,:User_ID,:Category_ID,:Income_ID,:Income_Amount)';
  qryRecords.ParamByName('DateofIncome').AsDateTIme := dDate;
  qryRecords.ParamByName('User_ID').AsInteger := SpinEdit2.Value;
  qryRecords.ParamByname('Category_ID').AsInteger := iCategory;
  qryRecords.ParamByname('Income_ID').AsInteger := iNameOfIncome;  
  qryRecords.ParamByname('Income_Amount').AsFloat:= sAmount;
  qryRecords.ExecSQL;

  qryRecords.SQL.Text := 'SELECT * FROM [Income (Ledger)] ORDER BY IncomeNo';
  qryRecords.Open;

这样您就可以将正确的类型传递给DB。否则你不知道db将如何解释你发送给它的内容。