Home > Software engineering >  Storing TTreeView inside SQL Server database table
Storing TTreeView inside SQL Server database table

Time:04-20

Am trying to store my TTreeView inside SQL Server database table by using the next procedure:

procedure Save;
var
  BlobField :TBlobField;
  Query:TADOQuery;
  Stream:TStream;
begin
  Stream := TMemoryStream.Create;
  Query := TADOQuery.Create(Self);
  Query.SQL.Add('Select * From MyTable') ;
  Query.Active := True;
  Query.First;
  Query.Edit;
  BlobField := Query.FieldByName('MyTableField') as TBlobField;
  Stream := Query.CreateBlobStream(BlobField, bmWrite);
  TreeView1.SaveToStream(Stream);
  Query.Refresh;
  Query.Free;
  Stream.Free;
end; 

But every time I am getting the error: DataSet is not in edit or insert mode.

I'm using Delphi 10.1, Win 10, SQL server 2019.

CodePudding user response:

Change Query.Refresh; to Query.Post;

Also, you need to Free the blob stream to finalize writing to the blob field before you then Post to commit the new data into the DB.

Also, you are leaking an unused TMemoryStream object.

Try this:

procedure Save;
var
  BlobField: TField;
  Query: TADOQuery;
  Stream: TStream;
begin
  Query := TADOQuery.Create(nil);
  try
    Query.SQL.Text := 'Select TOP(1) * From MyTable';
    Query.Open;
    try
      Query.First;
      Query.Edit;
      try
        BlobField := Query.FieldByName('MyTableField');
        Stream := Query.CreateBlobStream(BlobField, bmWrite);
        try
          TreeView1.SaveToStream(Stream);
        finally
          Stream.Free;
        end;
        Query.Post;
      except
        Query.Cancel;
        raise;
      end;
    finally
      Query.Close;
    end;
  finally
    Query.Free;
  end;
end; 
  • Related