从查询中获取结果

时间:2017-03-30 00:57:15

标签: delphi delphi-10-seattle firedac

我写这段代码:

Var Q : TFDQuery;
begin
Q := TFDQuery.Create(Self);
Q.Connection := FDConnection1;
Q.Params.CreateParam(ftString,'N',ptOutput);// Try also ptResult
Q.Params.CreateParam(ftInteger,'ID',ptInput);
Q.SQL.Text := 'SELECT NOM FROM EMPLOYEE WHERE ID_EMP = :ID';
Q.Params.ParamByName('ID').Value := 1;
Q.Active := True;
ShowMessage( VarToStr(Q.Params.ParamByName('N').Value) );

结果应该是雇主的名字。

我收到错误:

  

' N'参数未找到

如何使用参数?

从Query中获取结果

如果我不能,那么它的功能是什么:

  • ptOutput

  • ptResult

2 个答案:

答案 0 :(得分:3)

无需手动创建参数。数据访问组件足够智能,可以解析SQL字符串并自行填充参数集合

要获得结果,您还必须阅读查询的字段。在Query组件上调用 $(function () { /* user run query click event*/ $('#run_query').click(function () { populateDataTable(sample_ajax); }); function populateDataTable(json_obj) { console.log(json_obj) /*extract fields from ajax return*/ var keys = Object.keys(json_obj[0]); var columns_obj = []; $.each(keys, function (i, it) { columns_obj[i] = { data: it, title: it }; }); /*draw html table container*/ var html_table = '<table id="example" class="display" width="100%" cellspacing="0"><thead></thead><tbody></tbody></table>'; $('#query_output').html(html_table); $('#query_output table').DataTable({ data: json_obj, columns: columns_obj }); } }); 时,将使用您在Open SQL语句中指定的字段填充字段集合

作为旁注,我建议您使用类型安全版本从SELECT [fields]TField对象中获取值:See more here

TParameter

答案 1 :(得分:3)

试试这段代码:

procedure TForm1.ExecuteQuery;
var
  SQL : String;
  Q : TFDQuery;
begin
  SQL := 'select ''Sami'' as NOM';  //  Tested with MS Sql Server backend
  try
    Q := TFDQuery.Create(Self);
    Q.Connection := FDConnection1;
    Q.Params.CreateParam(ftString, 'Nom', ptOutput);// Try also ptResult
    Q.SQL.Text := SQL;
    Q.Open;
    ShowMessage( IntToStr(Q.ParamCount));
    Caption := Q.FieldByName('Nom').AsString;
  finally
    Q.Free;  // otherwise you have a memory leak
  end;
end;

一旦打开FDQuery,您将看到创建的参数不再存在,因为FireDAC&#34;知道&#34;它无能为力。

然后,将Q.Open替换为Q.ExecSQL。执行时会出现异常 消息

  

无法执行命令返回结果集。   提示:对类似SELECT的命令使用Open方法。

这就是你的问题。如果使用SELECT语句,则会得到结果集 你喜欢与否,访问其内容的方式是做

之类的事情
Nom := Q.FieldByName('Nom').AsString

您在评论中询问了ptOutput参数的重点。假设您的数据库有一个像这样定义的存储过程

  

创建过程spReturnValue(@Value varchar(80)out)   如   选择@Value =&#39;&#39;

然后,在您的代码中,您可以

  SQL := 'exec spReturnValue :Value';  //  note the absence of the `out` qualifier in the invocation of the SP

  try
    Q := TFDQuery.Create(Self);
    Q.Connection := FDConnection1;
    Q.Params.CreateParam(ftString, 'Value', ptOutput);// Try also ptResult
    Q.SQL.Text := SQL;
    Q.ExecSQL;
    ShowMessage( IntToStr(Q.ParamCount));
    Caption := Q.ParamByName('Value').AsString;
  finally
    Q.Free;  // otherwise you have a memory leak
  end;

,它将存储过程的输出参数检索到Q的Value参数。

相关问题