gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 04:07:14 25 4
gpt4 key购买 nike

我收到此错误消息:

List index out of bounds (1)

尝试从我的数据库中选择信息时。我正在使用 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 属性,并在访问内容中的项目时完全删除 Strings (StringsItems 的默认属性)。此外,您应该在循环中使用 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 注入(inject)。

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;

关于mysql - 为什么会出现列表索引越界 (1) 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28995114/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com