DELPHI模板编程

DELPHI模板编程

procedure TCRUD<T>.execsql(OnTableModel: TTableModel);
//执行事务性SQL
begin
  if req.Body = nil then
    Exit;
  var pool: TDBPool := GetDBPool(dbid);  //database pool
  db := pool.Lock;
  try
    try
      table := serialize.TSerial<TTable<T>>.unjson(TStream(req.Body));  //json string--->record
      db.startTrans;                //开启事务
      for var i: Integer := 0 to High(table.rows) do
      begin
        db.qry.Close;
        db.qry.SQL.Clear;
        db.qry.sql.add(sql);
        OnTableModel(db, table, i);  //set field value
        db.qry.ExecSQL;
      end;
      db.commitTrans;         //提交事务
      res.Send(success);
    except
      on E: Exception do
      begin
        db.rollbackTrans;     //回滚事务
        res.Send(error(E.Message));
        WriteLog(func + E.Message);
      end;
    end;
  finally
    pool.Unlock(db);
  end;
end;

procedure TCRUD<T>.open(OnTableModel: TTableModel);
//查询
begin
  var pool: TDBPool := GetDBPool(dbid);
  db := pool.Lock;
  try
    try
      var where: string;              //where条件
      if req.Body <> nil then
        where := TEncoding.UTF8.GetString(TBytesStream(req.Body).Bytes);
      var lsql: string;
      if where = '' then             //拼SQL查询命令
        lsql := sql
      else
        lsql := sql + ' where ' + where;
      db.select(lsql);       //查询
      SetLength(table.rows, db.qry.RecordCount);    //记录条数
      var i: Integer := 0;
      db.qry.First;                    //dataset--->record
      while not db.qry.Eof do
      begin
        OnTableModel(db, table, i);    //set field value
        db.qry.Next;
        Inc(i);
      end;
      res.Send(TSerial<TTable<T>>.json(table));   //send json string
    except
      on E: Exception do
      begin
        res.Send(error(E.Message));
        writelog(func + E.Message);
      end;
    end;
  finally
    pool.Unlock(db);
  end;
end;

  

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