论DATASNAP远程方法支持自定义对象作参数

时间:2023-02-04 11:57:06

论DATASNAP远程方法支持自定义对象作参数

DATASNAP远程方法已经可以支持自定义对象作参数,这是非常方便的功能。

1)自定义对象

type
TMyInfo = class(TObject)
public
AccountNo: string;
SQL: string;
Params: string;
end;

2)远程方法定义

function TServerMethods1.QuerySql4(const myInfo: TMyInfo): TFDJSONDataSets;
var
d: TfrmDB;
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
SetTraceOn(d);
d.qryOpen.Close;
d.qryOpen.sql.Clear;
d.qryOpen.sql.Text := myInfo.sql;
if myInfo.params <> '' then
StrToFDParams(myInfo.params, d.qryOpen.params);
d.qryOpen.Open;
Result := TFDJSONDataSets.Create;
TFDJSONDataSetsWriter.ListAdd(Result, '1', d.qryOpen);
except
on e: Exception do
begin
Result := nil;
Log.WriteLog('TServerMethods1.QuerySql4 ' + e.Message);
end;
end;
finally
d.qryOpen.Close;
GetDBPool(myInfo.accountNo).Unlock(d);
SetTraceOff(d);
end;
end;

3)客户端自动生成的远程方法接口

function TServerMethods1Client.QuerySql4(myInfo: TMyInfo): TFDJSONDataSets;
begin
if FQuerySql4Command = nil then
begin
FQuerySql4Command := FDBXConnection.CreateCommand;
FQuerySql4Command.CommandType := TDBXCommandTypes.DSServerMethod;
FQuerySql4Command.Text := 'TServerMethods1.QuerySql4';
FQuerySql4Command.Prepare;
end;
if not Assigned(myInfo) then
FQuerySql4Command.Parameters[0].Value.SetNull
else
begin
FMarshal := TDBXClientCommand(FQuerySql4Command.Parameters[0].ConnectionHandler).GetJSONMarshaler;
try
FQuerySql4Command.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(myInfo), True);
if FInstanceOwner then
myInfo.Free
finally
FreeAndNil(FMarshal)
end
end;
FQuerySql4Command.ExecuteUpdate;
if not FQuerySql4Command.Parameters[1].Value.IsNull then
begin
FUnMarshal := TDBXClientCommand(FQuerySql4Command.Parameters[1].ConnectionHandler).GetJSONUnMarshaler;
try
Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FQuerySql4Command.Parameters[1].Value.GetJSONValue(True)));
if FInstanceOwner then
FQuerySql4Command.FreeOnExecute(Result);
finally
FreeAndNil(FUnMarshal)
end
end
else
Result := nil;
end;

从代码中可以看出,DATASNAP自动将我们的自定义对象使用JSON序列和还原了。

4)客户端调用演示

procedure TForm1.Button3Click(Sender: TObject);
var
LDataSets: TFDJSONDataSets;
LDataSet: TFDDataSet;
myInfo: TMyInfo;
begin
DataSource1.DataSet := FDMemTable1;
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;