Databases

Using SQL query

Posted in Databases

If you want to select something from your database, then use Query component and SQL language. This example shows, how to select all records, where "Boa" value is in the "NAME" field.

procedure TForm1.Button1Click(Sender: TObject);
begin
  with Query1 do
  begin
    Active:=False;
    SQL.Clear;
    SQL.Add('Select * from animals where name="Boa"');
    Active:=True;
  end;
end;

Store rich text in database

Posted in Databases

For reading and writing data you can use BLOB stream feature of TTable:

procedure TForm1.Button2Click(Sender: TObject);
var
  Stream1: TStream;
begin
  Table1.Edit;
  Stream1:=Table1.CreateBlobStream(Table1.FieldByName('RTF'),bmReadWrite);
  RichEdit1.Lines.SaveToStream(Stream1);
  Table1.Post;
  RichEdit1.Clear;
end;

Sort columns in DBGrid

Posted in Databases

Use the FieldName property of the DBGrid to set an index with the same name as the FieldName.

procedure TForm1.DBGrid1TitleClick(Column: TColumn);
begin
  (Column.Field.DataSet as TTable).IndexFieldNames:=Column.FieldName;
end;

Set filter for database

Posted in Databases

ou may use Filter and Filtered properties of Table component. But for more difficult queries, you may use OnFilterRecord event of TTable. This example shows, how to show records, where AREA>1500000.

procedure TForm1.Table1FilterRecord(DataSet: TDataSet;
  var Accept: Boolean);
var
  Value: Integer;
begin
  Value:=Table1['Area'];
  Accept:=Value>1500000;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  Table1.Filtered:=True;
end;

Set colors for DBCtrlGrid's lines

Posted in Databases

Use the OnPaintPanel event:

procedure TForm1.DBCtrlGrid1PaintPanel(DBCtrlGrid: TDBCtrlGrid;
  Index: Integer);
begin
  if Odd(DBCtrlGrid1.DataSource.DataSet.RecNo) then
    DBCtrlGrid1.Color:=clRed
  else
    DBCtrlGrid1.Color:=clBlue;
end;