泛型模板编程

泛型模板编程

1)定义泛型模板

type
  TTable<T: record> = record      //单表
    rows: TArray<T>;              //表的行
  end;

  TTables<T, T2: record> = record  //多表
    table1: TTable<T>;             //表1
    table2: TTable<T2>;            //表2
  end;

2)定义计量单位模板

unit danwei.model;
/// <author>cxg 2023-8-30</author>
interface

type      //定义 数据模型(data-model)
  Tdanwei = record
    unitid: string;
    unitname: string;
  end;

implementation

end.

定义产品模板

unit product.model;
/// <author>cxg 2023-9-11</author>

interface

type
  Tproduct = record
    goodsid: string;
    jj: Double;
  end;

implementation

end.

  3)使用泛型模板

procedure TRESTdanwei.select2(const req: TRequest; const res: TResponse);
//多表查询
begin
  var pool: TDBPool := GetDBPool('1');
  var db: TDB := pool.Lock;
  try
    try
      var where: string;
      if req.Body <> nil then
        where := TEncoding.UTF8.GetString(TBytesStream(req.Body).Bytes);
      var sql: string;
      if where = '' then
        sql := 'select * from tunit'
      else
        sql := 'select * from tunit where ' + where;
      db.select(sql);
      var tables: TTables<Tdanwei, Tproduct>;   //2个表
      SetLength(tables.table1.rows, db.qry.RecordCount);
      var i: Integer := 0;
      db.qry.First;
      while not db.qry.Eof do
      begin
        tables.table1.rows[i].unitid := db.qry.FieldByName('unitid').AsString;
        tables.table1.rows[i].unitname := db.qry.FieldByName('unitname').AsString;
        db.qry.Next;
        Inc(i);
      end;
      sql := 'select goodsid,jj from tgoods';
      db.select(sql);
      SetLength(tables.table2.rows, db.qry.RecordCount);
      i := 0;
      db.qry.First;
      while not db.qry.Eof do
      begin
        tables.table2.rows[i].goodsid := db.qry.FieldByName('goodsid').AsString;
        tables.table2.rows[i].jj := db.qry.FieldByName('jj').AsFloat;
        db.qry.Next;
        Inc(i);
      end;
      res.Send(TSerial<TTables<Tdanwei, Tproduct>>.json(tables));
    except
      on E: Exception do
      begin
        res.Send(error(E.Message));
        writelog('TRESTdanwei.select2()' + E.Message);
      end;
    end;
  finally
    pool.Unlock(db);
  end;
end;

  4)apipost调用

 

posted @ 2023-09-12 09:41  delphi中间件  阅读(446)  评论(0编辑  收藏  举报