Databases

Detect DataBase changings

Posted in Databases

Use onUpdateData event for DataSource component if you want to detect data changings in database.

procedure TForm1.DataSource1UpdateData(Sender: TObject);
begin
  ShowMessage('Database was changed !!!');
end;

Define BDE alias

Posted in Databases

Use DbiAddAlias function with necessary parameters. Example shows adding STANDARD alias.

uses  DBIProcs, DBITypes;
...
procedure TForm1.Button3Click(Sender: TObject);
var
  AliasName, AliasPath: string;
begin
  AliasName:='TESTAlias2';
  AliasPath:='PATH:C:\Tools';
  Check(
    DbiAddAlias(
      nil, 
      PChar(AliasName), 
      nil, 
      PChar(AliasPath), 
      True));
end;

Date format in database

Posted in Databases

Sometimes it is necessary to change a date format of date field, when you show data from your database. You may use DisplayFormat property of TDateField type.

procedure TForm1.FormCreate(Sender: TObject);
begin
  with table1 do
  begin
    TDateField(FieldByName('Date1')).DisplayFormat:='dd*mm*yyyy';
    TDateField(FieldByName('Date2')).DisplayFormat:='ddmmyyyy';
    Active:=True;
  end;
end;

Create TTable without a form

Posted in Databases

Actually you don't need to use any visual component. Remember that each component in Delphi is an object and do not forget to free it for releasing of the allocated memory.

uses Db, DBTables, Dialogs

procedure TForm1.Button1Click(Sender: TObject);
var
  Session: TSession;
  Database: TDatabase;
  Table: TTable;
begin
  Session:=TSession.Create(nil);
  Database:=TDatabase.Create(nil);
  Session.SessionName:='DBSession';
  Database.Connected:=False;
  Database.AliasName:='dbdemos';
  Database.DatabaseName:='biolife';
  Database.SessionName:=Session.SessionName;

  Table:=TTable.Create(nil);
  Table.DatabaseName:=Database.DatabaseName;
  Table.SessionName:=Session.SessionName;
  Table.TableName:='biolife';

  Table.Active:=True;
  ShowMessage(Table.Fields[1].AsString+' '+Table.Fields[2].AsString);
  Table.Free;
  Database.Free;
  Session.Free;
end;

Create DBGrid with colored cells

Posted in Databases

Use OnDrawColumnCell event of DBGrid component with the following code. This example will paint each cell to green color, if these cells are odd.

procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect;
  DataCol: Integer; Column: TColumn; State: TGridDrawState);
var
  HoldColor: TColor;
begin
  HoldColor:=DBGrid1.Canvas.Brush.Color; 
  if Column.FieldName='EmpNo' then 
    if (Column.Field.AsInteger mod 2 <> 0) then 
    begin
      DBGrid1.Canvas.Brush.Color:=clGreen;
      DBGrid1.DefaultDrawColumnCell(Rect, DataCol, Column, State);
      DBGrid1.Canvas.Brush.Color:=HoldColor;
    end;
end;