【问题标题】:Function with Variant Parameter带变量参数的函数
【发布时间】:2019-02-20 08:11:56
【问题描述】:

我创建了一个函数来刷新带有参数的查询,然后找到一个特定的字段。

function RefreshQuery(AQuery : TADOQuery; AField : string; AValue : integer; AParam : string; AParamValue : Variant) : boolean; overload;

当 AValue 为整数时,它可以工作,当我将其更改为 Variant 时

我收到 List Index Out of Bounds 1699364 错误

函数本身看起来像这样:

function RefreshQuery(AQuery : TADOQuery; AField : string; AValue : integer; AParam : string; AParamValue : Variant) : boolean; overload;
var AfterOpen,AfterScroll,BeforeOpen : TDataSetNotifyEvent;
    AList : TStringList;
    i : integer;
begin
  result:=false;

  AfterOpen := AQuery.AfterOpen;
  AfterScroll := AQuery.AfterScroll;
  BeforeOpen := AQuery.BeforeOpen;

  AQuery.AfterOpen:=nil;
  AQuery.AfterScroll:=nil;
  AQuery.BeforeOpen:=nil;

  AList := TStringList.Create;
  AList.Delimiter:=';';
  AList.DelimitedText:=AParam;

  if AQuery.Active then AQuery.Close;

  if AList.Count = 1 then
    AQuery.Parameters.ParamByName(AList[i]).Value:=AParamValue // the error happens here
  else
    for i := 0 to AList.Count-1 do
      AQuery.Parameters.ParamByName(AList[i]).Value:=AParamValue[i];

  AQuery.Open;

  if not AQuery.Locate(AField, AValue, []) then
    result:=false
  else
    result:=true;

  AQuery.AfterOpen:=AfterOpen;
  AQuery.AfterScroll:=AfterScroll;
  AQuery.BeforeOpen:=BeforeOpen;

  if Assigned(AQuery.AfterScroll) then
    AQuery.AfterScroll(AQuery);

  AList.Free;
end;

我是这样使用它的:

  if   RefreshQuery(CityQuery,'id',CityQueryID.Value,'Active',not(CheckBox1.Checked).ToInteger+2) = false then
  begin
    MessageDlg('blabla!',mtWarning, [mbOK], 0);
    Exit;
  end;

在上面的例子中 CityQueryID.Value 是 Integer Type 。但有时我想使用 String 。所以我想更改函数以使用变体。

【问题讨论】:

  • 编译后,“查看”->“消息”。看看编译器有没有什么要说的。

标签: function delphi variant tadoquery


【解决方案1】:

错误发生是因为在语句中

  if AList.Count = 1 then
    AQuery.Parameters.ParamByName(AList[i]).Value:=AParamValue // the error happens here

您还没有为i 赋值,因为它是一个局部变量,它会有一个随机值,这取决于调用RefreshQuery 之前堆栈中的内容。

将语句改为

  if AList.Count = 1 then
    AQuery.Parameters.ParamByName(AList[0]).Value:=AParamValue

应该解决问题。

一旦你这样做了,你应该会发现你可以毫无问题地将AValue的参数类型更改为variant

【讨论】:

  • @RudyVelthuis:谢谢。我有一种有趣的感觉,你会发现编辑无法抗拒 .
  • @MartynA:删除错误(或指示错误的 cmets)非常令人满意。
猜你喜欢
  • 2012-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多