为什么会出现列表索引越界 (1) 错误?

Why am I getting list index out of bounds (1) error?

我收到此错误消息:

List index out of bounds (1)

尝试从我的数据库中 select 信息时。我正在使用 Delphi XE7、MySQL 6.2、FDConnection 和 FDQuery。我的代码是:

Procedure TAppointmentForm.GetTreatPrice;
Begin
  TreatPriceQuery.SQL.Text:= 'Select Cost from Treatment where TreatName = '+quotedstr(Treatment)+'';
  TreatPriceQuery.Open;
  TreatPrice:= TreatPriceQuery.FieldByName('Cost').AsInteger;
End;

我正在使用 CheckBoxList 来获取 Treatment。我的代码是:

Procedure TAppointmentForm.GetAppCost;
Var
  Count: Integer;
begin
  for Count := 0 to (Count1-1) do
    Begin
      if TreatmentCheckListBox.State[Count] = cbChecked then
        Begin
          Treatment:= TreatmentCheckListBox.Items.Strings[Count];
          GetTreatPrice;
          AppCost:= AppCost + TreatPrice;
        End
      Else
        AppCost:= AppCost;
    End;
end;

您的代码过于复杂。您可以使用 TCheckListBoxChecked 属性 并在访问内容中的项目时完全删除 StringsStrings 是默认的 属性 的 Items)。此外,您应该在循环中使用 ItemsCount

Procedure TAppointmentForm.GetAppCost;
Var
  Idx: Integer;
begin
  for Idx := 0 to TreatmentCheckListBox.Items.Count - 1 do
  Begin
    if TreatmentCheckListBox.Checked[Idx] then
    Begin
      Treatment:= TreatmentCheckListBox.Items[Idx];
      GetTreatPrice;
      AppCost:= AppCost + TreatPrice;
    End;
  // The next two lines are a non operation. Assigning a
  // variable to itself does nothing. Remove them entirely
 // Else
 //  AppCost:= AppCost;
    End;
end;

此外,停止为您的 SQL 连接文本,而是使用参数化查询,以提高效率和防止 SQL 注入。

Procedure TAppointmentForm.GetTreatPrice;
Begin
  TreatPriceQuery.SQL.Text:= 'Select Cost from Treatment where TreatName = :TreatName';
  TreatPriceQuery.ParamByName('TreatName').AsString := Treatment;
  TreatPriceQuery.Open;
  TreatPrice:= TreatPriceQuery.FieldByName('Cost').AsInteger;
End;

我也同意@Remy 在对你的问题的评论中的内容。您应该传递参数而不是使用全局变量。

function TAppointmentForm.GetTreatPrice(const TreatmentName: String): Integer;
Begin
  TreatPriceQuery.SQL.Text:= 'Select Cost from Treatment where TreatName = :TreatName';
  TreatPriceQuery.ParamByName('TreatName').AsString := TreatmentName;
  TreatPriceQuery.Open;
  Result := TreatPriceQuery.FieldByName('Cost').AsInteger;
End;

Procedure TAppointmentForm.GetAppCost;
Var
  Idx: Integer;
begin
  AppCost := 0;
  for Idx := 0 to TreatmentCheckListBox.Items.Count - 1 do
  Begin
    if TreatmentCheckListBox.Checked[Idx] then
    Begin
      AppCost := AppCost + GetTreatPrice(TreatmentCheckListBox.Items[Idx]);
    End;
  End;
end;