#1 2011-10-06 13:49:54

proto
Member
From: Russia, Kostroma
Registered: 2011-09-12
Posts: 31

Bypass fields

i load data to sqlite database from csv, procedure work fine:


class procedure TSQLPopulation.CreatePopulation(const ADatabase: TSQLRest);
var
  i, j: integer;
  population: TSQLPopulation;
  sl, slES: TStringlist;
begin
  sl := TStringList.Create;
  sl.LoadFromFile('Population.csv');
  slES := TStringList.Create;

  for i := 0 to sl.Count - 1 do begin
    slES.Clear;
    ExtractStrings([';'], [' '], PChar(sl.Strings[i]), slES);
    population := TSQLPopulation.Create(Database, 'Region = "%"', [slES.Strings[0]]);
    try
      with population do
        if ID = 0 then begin
          fRegion  := slES.Strings[0];
          fAll2011 := StrToInt(slES.Strings[1]);
          fM2011   := StrToInt(slES.Strings[2]);
          fW2011   := StrToInt(slES.Strings[3]);
          FAll2012 := StrToInt(slES.Strings[4]);
          fM2012   := StrToInt(slES.Strings[5]);
          fW2012   := StrToInt(slES.Strings[6]);

          Database.Add(population, true);
        end
    finally
      FreeAndNil(population);
    end;
  end;

  sl.Free;
  slES.Free;
end;

but i want to automate the bypass fields

class procedure TSQLPopulation.CreatePopulation(const ADatabase: TSQLRest);
var
  i, j: integer;
  population: TSQLPopulation;
  sl, slES: TStringlist;
  v: Variant;
begin
  sl := TStringList.Create;
  sl.LoadFromFile('Population.csv');
  slES := TStringList.Create;

  for i := 0 to sl.Count - 1 do begin
    slES.Clear;
    ExtractStrings([';'], [' '], PChar(sl.Strings[i]), slES);
    population := TSQLPopulation.Create(Database, 'Region = "%"', [slES.Strings[0]]);
    try
      with population do
        if ID = 0 then begin
          for j := 0 to slES.Count - 1 do begin
            v := slES.Strings[j];
            SetFieldVarData(j , TVarData(v));
          end;

          Database.Add(population, true);
        end
    finally
      FreeAndNil(population);
    end;
  end;

  sl.Free;
  slES.Free;
end;

and this code not work(((

Offline

#2 2011-10-06 16:42:59

ab
Administrator
From: France
Registered: 2010-06-21
Posts: 14,240
Website

Re: Bypass fields

I think you still don't understand what the TVarData is made for in the SetFieldVarData() method. As stated by the documentation it is NOT a true variant type. So you can NOT type-cast the value as you write.

You can use the following trick:

  population.RecordProps.Fields[j].SetValue(population,pointer(StringToUTF8(slES.Strings[j])));

   

But I definitively NOT recommend such tricks, because it will follow the TSQLPopulation field order, which may change. You will loose one big benefit of the ORM aspect of the framework.   Your first version using Population fields is definitively better for me.

Offline

Board footer

Powered by FluxBB