如何将字符串转换为日期以操纵数据库

时间:2017-10-21 09:34:56

标签: sql delphi-7 ado

我是编码新手并且有一个学校项目。 我试图将字符串转换为日期,以便从数据库更新/删除记录,但它不断给我一个Data type mismatch in criteria expression错误。数据库中的字段(预订日期)被验证为日期,我试图将我的字符串输入转换为日期格式,然后从我的数据库中删除它的整个记录​​。

   sdelete:= combobox.text;  //shows options of dates
    Year := StrToInt(Copy(sdelete, 1, 4));
    Month := StrToInt(Copy(sdelete, 6, 2));
    day := StrToInt(Copy(sdelete, 9,2));
    date := EncodeDate(Year, Month,Day);
 end;//Converting to date format

`ADOdelete.SQL.Text := 'SELECT * FROM [scout] WHERE ([Password] =  
"'+Sscout+'"AND [date booked] ="'+FormatDateTime('yyyy/mm/dd',Date)+'")';`
   ADOdelete.Open;
   ADOdelete.Close;
ADOdelete.SQL.Text:= 'Delete from [scout] WHERE ([date booked] 
     ="'+FormatDateTime('yyyy/mm/dd',Date)+'"AND [password]="'+sscout+'")';
   ADOdelete.ExecSQL;
   ADOdelete.Free;` 

[Scout]是表名 和Sscout是一个保存密码的私有变量。 组合框由数据库中的金额填充([预订日期])并显示为yyyy/mm/dd 我有以下变量

var       sdelete:string;
          Day, Month, Year: Word;
          date:Tdatetime;

谢谢。

1 个答案:

答案 0 :(得分:2)

您应该使用parameterized queries代替。让DB驱动程序为您处理转义和格式化。例如:

var
  sDelete: string;
  dtBooked: TDate;
  fmt: TFormatSettings;
begin
  sDelete := ComboBox.Text; //shows options of dates

  fmt := TFormatSettings.Create;
  fmt.DateSeparator := '/'; // or '-' depending on your needs...
  fmt.ShortDateFormat := 'yyyy/mm/dd';
  dtBooked := StrToDate(sDelete, fmt);

  ADOdelete.SQL.Text := 'SELECT * FROM [scout] WHERE ([Password] = :password AND [date booked] = :booked)';
  ADOdelete.Parameters.ParamByName('password').Value := sScout;
  ADOdelete.Parameters.ParamByName('booked').Value := dtBooked;
  ADOdelete.Open;
  ...
  ADOdelete.SQL.Text := 'Delete from [scout] WHERE ([date booked] = :booked AND [password] = :password)';
  ADOdelete.Parameters.ParamByName('booked').Value := dtBooked;
  ADOdelete.Parameters.ParamByName('password').Value := sScout;
  ADOdelete.ExecSQL;
  ...
end;