欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Delphi开发系列(9):修改客户端数据后更新到数据库

程序员文章站 2023-12-22 17:15:52
...

数据包装成JSon对象传到服务器端

procedure TForm1.Button2Click(Sender: TObject);
var
  data: string;
  strSQL: string;
  Delta: string;
  AStream: TStringStream;
  JSon: TJSonObject;
begin
  AStream := TStringStream.Create('', TEncoding.UTF8);
  JSon:= TJSonObject.Create;
  try
    RESTClient1.BaseURL := 'http://10.238.218.14:18022/datasnap/rest/TServerMethods1/DBTable/abc';
    RESTClient1.Authenticator := HTTPBasicAuthenticator1;

    if FDMemTable1.State in dsEditModes then
      FDMemTable1.Post;
    if FDMemTable1.ChangeCount = 0 then
      Exit;

    FDMemTable1.ResourceOptions.StoreItems := [siDelta, siMeta];
    FDMemTable1.SaveToStream(AStream, sfJSON);
    Delta := AStream.DataString;
    Memo1.Text := Delta;

    strSQL := 'select OrgCode,OrgName from MTS_Org where Upper(OrgEntry)=''ROOT''';
    JSon.AddPair('strSQL', strSQL);
    JSon.AddPair('DBAlias', 'ORACLE');
    JSon.AddPair('Delta',Delta);

    RESTRequest1.Method := TRESTRequestMethod.rmPost;
    RESTRequest1.Params.Clear;
    RESTRequest1.Body.ClearBody;
    RESTRequest1.AddBody(Format('{"data":"%s"}',[gFun.Encrypt(JSon.ToJSON,CONST_SM4_KEY)]), ctAPPLICATION_JSON);
    RESTRequest1.Execute;
  finally
    FDMemTable1.ResourceOptions.StoreItems := [siDelta, siMeta, siData];
    AStream.Free;
    JSon.Free;
  end;
end;

Delphi开发系列(9):修改客户端数据后更新到数据库

服务器端更新数据方法:

function TServerMethods1.updateDBTable(Value: string; Obj: TJSONObject): string;
var
  strSQL: string;
  DBAlias: string;
  strErrMsg : string;
  AStream: TStringStream;
  i : Integer;
  Json: TJSONObject;
  Delta: string;
  data: string;
begin
  if Obj<>nil then
    begin
      data := obj.GetValue('data').Value;
      data := gFun.Decrypt(data,CONST_SM4_KEY);
      Json := TJSONObject.ParseJSONValue(data) as TJSONObject;
      strSQL := Json.GetValue('strSQL').Value;
      DBAlias := Json.GetValue('DBAlias').Value;
      Delta := Json.GetValue('Delta').Value;
    end;
  if (DBAlias='')or(strSQL='')or(Delta='') then
    begin
      Result := '更新失败:没有接收到正确的更新数据!';
      Exit;
    end;
  FDConnection.ConnectionDefName := DBAlias;
  AStream := TStringStream.Create(Delta, TEncoding.UTF8);
  try
    try
      FDConnection.Connected := True;
      FDQuery.Connection := FDConnection;
      FDQuery.SQL.Text := strSQL;
      AStream := TStringStream.Create(Delta, TEncoding.UTF8);
      AStream.position := 0;
      FDQuery.LoadFromStream(AStream, sfJSON);
      FDQuery.ApplyUpdates(i);
    except
      on E: Exception do
      begin
        strErrMsg := 'TServerMethods1.EchoString: ' + E.Message;
      end;
    end;
  finally
    AStream.Free;
  end;
end;

Delphi开发系列(9):修改客户端数据后更新到数据库

相关标签: Delphi

上一篇:

下一篇: