有同仁需要远程方法传输自定义的数据类型,他以为要自己写代码会很复杂,其实DATASNAP早就为我们想到了。
datasnap的数据序列和还原真是无与伦比的强大,其远程方法支持自定义对象传参,DATASNAP会自动使用JSON序列和还原自定义的对象。
1)自定义一个对象
type
TMyInfo = class(TObject)
public
AccountNo: string;
SQL: string;
Params: string;
RecsMax: Integer;
end;
2)服务端远程方法定义
function TServerMethods1.QuerySql4(const myInfo: TMyInfo): TFDJSONDataSets;
var
d: TfrmDB;
i, iPos: Integer;
sl: TStringList;
LName, LValue, LStr: string;
p: TFDParam;
begin
Result := nil;
if not Assigned(myInfo) then
Exit;
if (myInfo.AccountNo = ‘‘) or (myInfo.SQL = ‘‘) then
Exit;
d := GetDBPool(myInfo.AccountNo).Lock;
if not Assigned(d) then
Exit;
try
try
d.qryOpen.Close;
d.qryOpen.sql.Clear;
d.qryOpen.sql.Text := myInfo.SQL;
if myInfo.Params <> ‘‘ then
begin
sl := TStringList.Create;
try
sl.Delimiter := ‘;‘;
sl.DelimitedText := myInfo.Params;
for i := 0 to sl.Count - 1 do
begin
LStr := sl.Strings[i];
iPos := Pos(‘:‘, LStr);
LName := LeftStr(LStr, iPos - 1);
LValue := RightStr(LStr, Length(LStr) - iPos);
p := d.qryOpen.FindParam(LName);
if p <> nil then
p.Value := LValue;
end;
finally
sl.Free;
end;
end;
d.qryOpen.Open;
Result := TFDJSONDataSets.Create;
TFDJSONDataSetsWriter.ListAdd(Result, ‘1‘, d.qryOpen);
except
on e: Exception do
begin
Result := nil;
Log.WriteLog(‘TServerMethods1.QuerySql2 ‘ + e.Message);
end;
end;
finally
d.qryOpen.Close;
GetDBPool(myInfo.AccountNo).Unlock(d);
end;
end;
3)客户端调用
procedure TForm1.Button3Click(Sender: TObject);
var
LDataSets: TFDJSONDataSets;
LDataSet: TFDDataSet;
myInfo: TMyInfo;
begin
myinfo := TMyInfo.Create;
myInfo.AccountNo := ‘0‘;
myInfo.SQL := ‘select * from t1 where c1=:c1‘;
myInfo.Params := ‘c1:55‘;
LDataSets := methods.QuerySql4(myInfo);
LDataSet := TFDJSONDataSetsReader.GetListValueByName(LDataSets, ‘1‘);
FDMemTable1.Close;
FDMemTable1.Data := LDataSet;
end;