我写了这样一个函数
function SQLExec(cnn, cmd, rst: OleVariant; const SQL: string; prms: TParameters_): Boolean;
var
  i: Longint;
begin
  Result := not (VarIsEmpty(cnn) or VarIsEmpty(cmd)) and (cnn.State = adStateOpen);
  if Result then
  begin
    try
      cmd.CommandText      := SQL;
      cmd.CommandType      := adCmdText;
      cmd.ActiveConnection := cnn;      for i := Low(prms) to High(prms) do
        case prms[i].Direction of
          adParamInput, adParamInputOutput:
            cmd.Parameters[prms[i].Name].Value := prms[i].Value;
        end;
      cmd.Prepared := True;
      rst := cmd.Execute;    except
      Result := False;
    end;
  end;
end;用来执行带参数的sql语句,update语句执行没有问题,但是在执行select语句时,结果集rst的RecordCount 为 -1,对其进行操作时提示“对象关闭时,不允许操作”,请大侠帮忙看看问题出在哪里,不胜感激!!

解决方案 »

  1.   

    rst.ActiveConnection := cnn;  加这句试
    rst := cmd.Execute; 
      

  2.   

    贴上你的select所以语句另外加上rst.Activeconnection := cnn;
      

  3.   

    cmd.Execute能返回数据集吗?update不需要返回数据集,故不会出错;而select却需要返回数据集,所以出错我认为要分两种情况:
    1、sql语句的第一个单词的大写是SELECT ,就用open (用TAdoQuery.Open)
    2、其他情况用execute
      

  4.   

    在Delphi中使用原生ADO控制数据库
      

  5.   

    这是我的调用
    var
      sql, ConStr : string;
      prms: TParameters_;
      cnn, rst, cmd: OleVariant;
    begin
      cnn := CreateConnection;
      rst := CreateRecordset;
      cmd := CreateCommand;  ConStr := '略';
      try
        try
          ConnectToDB(cnn,'','',ConStr);      sql :='select * from User where Name = :Name';
          SetLength(prms,1);      prms[0].Name      := ':Name';
          prms[0].Direction := adParamInput;
          prms[0].Value     := 'ccc';      SQLExec(cnn, cmd, rst,sql,prms);      showmessage(inttostr(rst.RecordCount));
        except
          //
        end;
      finally
        FreeCommand(cmd);
        FreeRecordset(rst);
        FreeConnection(cnn);
      end;
    end;改成这样也不行啊,各位大侠再帮忙看看啊!!!!
    function SQLExec(cnn, cmd, rst: OleVariant; const SQL: string; prms: TParameters_): Boolean;
    var
      i: Longint;
    begin
      Result := not (VarIsEmpty(cnn) or VarIsEmpty(cmd)) and (cnn.State = adStateOpen);
      if Result then
      begin
        try
          cmd.CommandText      := SQL;
          cmd.CommandType      := adCmdText;
          cmd.ActiveConnection := cnn;      for i := Low(prms) to High(prms) do
            case prms[i].Direction of
              adParamInput, adParamInputOutput:
                cmd.Parameters[prms[i].Name].Value := prms[i].Value;
            end;      rst.ActiveConnection := cnn;
          rst                  := cmd.Execute;
        except
          Result := False;
        end;
      end;
    end;
      

  6.   

    我认为问题出在这里rst := cmd.Execute; 使用T Q u e r y可以执行两种查询:一种是返回结果集的,另一种是不返回结果集的。对于返回结果集的查询,应当调用T Q u e r y. O p e n ( )方法。而对不返回结果集的查询,则使用T Q u e r y. E x e c S Q L ( )方法。
    到ADO中也一样,同样是Query