代码之家  ›  专栏  ›  技术社区  ›  Funk247

运算符未重载:“常量字符串”+“非类型”

  •  0
  • Funk247  · 技术社区  · 11 年前

    我正在从数据集读取一个SQL函数,然后将其写入一个文件,我创建了一个小过程,检查空字段,然后将它们替换为null,非空的字段周围有引号。

    然而,当我编译时,我得到了错误

    Error: Operator is not overloaded: "Constant String" + "untyped"
    

    坦率地说,我不知道这意味着什么,我查看了fpc解析器消息帮助,其中写道

    You’re trying to use an overloaded operator when it is not overloaded for this type.
    

    我觉得这更令人困惑。有人能帮我吗?我认为这是因为我在程序中进行了比较,但可能是错误的。

    procedure isNull(str : AnsiString);
      begin
        if str = EmptyStr then
          str := Null
        else
          str := '' + str + '';
      end;
    
    procedure TForm1.Button2Click(Sender: TObject);
    var
      i : Integer;
      addLine, f : string;
      list : TStringList;
    begin
      f := 'info.sql';
      list := TStringList.Create;
    
      with AddressData do begin
        for i := 0 to RecordCount do begin
    
        RecNo := i;
        addLine := 'CALL CONT__Add(' + isNull(Fields[0].AsString) +')'; // Much more of this but fails at first call of procedure
        list.Add(addLine);
        end;
      list.SaveToFile(f);
      list.free;
       end;
    end;
    
    3 回复  |  直到 11 年前
        1
  •  2
  •   David Heffernan    11 年前
    addLine := 'CALL CONT__Add(' + isNull(Fields[0].AsString) +')';
    

    失败的原因是 isNull 是一个过程,因此不评估任何内容。为了编译此代码 isNull 需要是一个返回类型可以强制为字符串的函数。

    我发现很难知道你应该如何改变你的程序,因为它试图做什么并不明显 isNull 应针对null测试其输入并返回布尔值。

    我也承认在

    str := '' + str + '';
    

    这根本不起作用,对 str .

    我最好的猜测是你想要这样的东西:

    function PrepareField(const str: string): string;
    begin
      if str = '' then
        Result := Null
      else
        Result := '''' + str + '''';
    end;
    

    这段代码让我担心SQL注入。你考虑过风险了吗?

        2
  •  0
  •   Funk247    11 年前

    定义isNull如下编译。谢谢大卫的指点。

    function isNull(str : AnsiString) : String;
    begin
      if str = EmptyStr then
        str := Null
      else
        str := '' + str + '';
      isNull := str;
    end; 
    
        3
  •  0
  •   Abelisto    11 年前

    代码中有几个错误

    procedure isNull(str : AnsiString); // str assignments inside procedure does not takes effect outside procedure, use var str
      begin
        if str = EmptyStr then
          str := Null // Incompatible types AnsiString (str) and Variant (Null). May be you means 'Null' (in quotes)?
        else
          str := '' + str + ''; // concatenation with empty strings, use QuotedStr(str)
      end;
    

    正如@DavidHeffernan所说 isNull 是一个过程,不能以函数方式使用。