https://wiki.freepascal.org/api.php?action=feedcontributions&user=Mario13&feedformat=atomLazarus wiki - User contributions [en]2024-03-28T19:00:08ZUser contributionsMediaWiki 1.35.6https://wiki.freepascal.org/index.php?title=TDateTime&diff=155593TDateTime2023-01-29T15:14:50Z<p>Mario13: </p>
<hr />
<div>{{TDateTime}}<br />
<br />
TDateTime is stored as a double, the integer part representing days and the fractional part being fraction of a day. The integer part is the number of days that have passed since December 30, 1899, and can be a negative number. The fractional part reflects the fraction of a 24-hour day without regard to the sign of the TDateTime value, so care must be taken when computing negative TDateTime values with a fractional part.<br /><br />
Methods exist in Sysutils (datetimeroutines) that allow reading, writing and calculating with TDateTime, converting to and from a number of formats.<br /><br />
The following table displays examples of TDateTime values and their corresponding dates and times: <br />
<br />
{| class="wikitable" style="margin:auto"<br />
!Double Value !! 'dd-mm-yyyy hh:nn:ss'<br />
|-<br />
| -1.75 || 29-12-1899 18:00:00<br />
|-<br />
| -1.5 || 29-12-1899 12:00:00<br />
|-<br />
| -1.25 || 29-12-1899 06:00:00<br />
|-<br />
| 0 || 30-12-1899 00:00:00<br />
|-<br />
| 1.25 || 31-12-1899 06:00:00<br />
|-<br />
| 2.25 || 01-01-1900 06:00:00<br />
|-<br />
| 25569 || 01-01-1970 00:00:00 (Unix Epoch)<br />
|-<br />
| 36152.5 || 23-12-1998 12:00:00 (FPC 1.0 Beta2)<br />
|-<br />
| 36526 || 01-01-2000 00:00:00<br />
|-<br />
| 44927 || 01-01-2023 00:00:00 <br />
|}<br />
<br />
<br />
== Get current time ==<br />
<br />
[[Unit]] SysUtils [[Function|function]] Now retrieves the current system date and time.<br />
<br />
<syntaxhighlight lang="pascal"><br />
function Now : TDateTime; <br />
</syntaxhighlight><br />
<br />
== Adding and subtracting TDateTime ==<br />
<br />
Unit DateUtils function DaysBetween tell number of whole days between two DateTime values.<br />
<br />
<syntaxhighlight lang="pascal"><br />
function DaysBetween ( const ToDate, FromDate : TDateTime ) : Integer;<br />
</syntaxhighlight><br />
<br />
Unit DateUtils function WeeksBetween tell number of whole weeks between two DateTime values.<br />
<br />
<syntaxhighlight lang="pascal"><br />
function WeeksBetween( const ToDate, FromDate : TDateTime ):Integer;<br />
</syntaxhighlight><br />
<br />
<br />
<br />
<syntaxhighlight lang="pascal"><br />
<br />
program DateProject1;<br />
<br />
uses<br />
SysUtils,DateUtils;<br />
const<br />
DateFormatChars = 'dd"/"mm"/"yyyy';<br />
var<br />
DateTime1, DateTime2: TDateTime;<br />
begin<br />
DateTime1 := now;<br />
DateTime2 := DateTime1 + 4*7; //28 days later<br />
WriteLn('Current date is '+ FormatDateTime( DateFormatChars, DateTime1 ));<br />
WriteLn('28 days later date is '+ FormatDateTime( DateFormatChars, DateTime2 ));<br />
WriteLn('Number of days is '+ ( DaysBetween( DateTime1 ,DateTime2)).ToString );<br />
WriteLn('Number of weeks is '+ ( WeeksBetween( DateTime1 ,DateTime2)).ToString );<br />
ReadLn;<br />
end. <br />
<br />
</syntaxhighlight><br />
<br />
== Set Date ==<br />
<br />
Unit SysUtils function EncodeDate to set the date.<br />
<br />
<syntaxhighlight lang="pascal"><br />
function EncodeDate ( const Year, Month, Day : Word ) : TDateTime; <br />
</syntaxhighlight><br />
<br />
== Compare two TDateTime ==<br />
<br />
<br />
<syntaxhighlight lang="pascal"><br />
<br />
program CompareTwoDateTime;<br />
<br />
uses<br />
SysUtils, DateUtils;<br />
var<br />
firstDate, secondDate: TDateTime;<br />
begin<br />
firstDate := EncodeDate(2000, 2, 29);<br />
secondDate := EncodeDate(2018, 8, 11);<br />
if DaysBetween( firstDate, secondDate) = 0<br />
then WriteLn('Both dates are same')<br />
else<br />
if firstDate < secondDate<br />
then WriteLn('First date is earlier')<br />
else WriteLn('First date is later');<br />
ReadLn;<br />
end. <br />
</syntaxhighlight><br />
<br />
== See also ==<br />
<br />
* Date and time format [[ISO 8601]]<br />
* [[RFC 1123 Time Format]]<br />
* {{Doc|package=RTL|unit=sysutils|identifier=datetimeroutines|Date and time routines}} in the [[sysutils|<syntaxhighlight lang="pascal" inline>sysUtils</syntaxhighlight> unit]]</div>Mario13https://wiki.freepascal.org/index.php?title=TDateTime&diff=155592TDateTime2023-01-29T14:49:29Z<p>Mario13: </p>
<hr />
<div>{{TDateTime}}<br />
<br />
TDateTime is stored as a double, the integer part representing days and the fractional part being fraction of a day. The integer part is the number of days that have passed since December 30, 1899, and can be a negative number. The fractional part reflects the fraction of a 24-hour day without regard to the sign of the TDateTime value, so care must be taken when computing negative TDateTime values with a fractional part.<br /><br />
Methods exist in Sysutils (datetimeroutines) that allow reading, writing and calculating with TDateTime, converting to and from a number of formats.<br /><br />
The following table displays examples of TDateTime values and their corresponding dates and times: <br />
<br />
{| class="wikitable" style="margin:auto"<br />
!Double Value !! 'dd-mm-yyyy hh:nn:ss'<br />
|-<br />
| -1.75 || 29-12-1899 18:00:00<br />
|-<br />
| -1.5 || 29-12-1899 12:00:00<br />
|-<br />
| -1.25 || 29-12-1899 06:00:00<br />
|-<br />
| 0 || 30-12-1899 00:00:00<br />
|-<br />
| 1.25 || 31-12-1899 06:00:00<br />
|-<br />
| 2.25 || 01-01-1900 06:00:00<br />
|-<br />
| 25569 || 01-01-1970 00:00:00 (Unix Epoch)<br />
|-<br />
| 36526 || 01-01-2000 00:00:00<br />
|-<br />
| 44927 || 01-01-2023 00:00:00 <br />
|}<br />
<br />
<br />
== Get current time ==<br />
<br />
[[Unit]] SysUtils [[Function|function]] Now retrieves the current system date and time.<br />
<br />
<syntaxhighlight lang="pascal"><br />
function Now : TDateTime; <br />
</syntaxhighlight><br />
<br />
== Adding and subtracting TDateTime ==<br />
<br />
Unit DateUtils function DaysBetween tell number of whole days between two DateTime values.<br />
<br />
<syntaxhighlight lang="pascal"><br />
function DaysBetween ( const ToDate, FromDate : TDateTime ) : Integer;<br />
</syntaxhighlight><br />
<br />
Unit DateUtils function WeeksBetween tell number of whole weeks between two DateTime values.<br />
<br />
<syntaxhighlight lang="pascal"><br />
function WeeksBetween( const ToDate, FromDate : TDateTime ):Integer;<br />
</syntaxhighlight><br />
<br />
<br />
<br />
<syntaxhighlight lang="pascal"><br />
<br />
program DateProject1;<br />
<br />
uses<br />
SysUtils,DateUtils;<br />
const<br />
DateFormatChars = 'dd"/"mm"/"yyyy';<br />
var<br />
DateTime1, DateTime2: TDateTime;<br />
begin<br />
DateTime1 := now;<br />
DateTime2 := DateTime1 + 4*7; //28 days later<br />
WriteLn('Current date is '+ FormatDateTime( DateFormatChars, DateTime1 ));<br />
WriteLn('28 days later date is '+ FormatDateTime( DateFormatChars, DateTime2 ));<br />
WriteLn('Number of days is '+ ( DaysBetween( DateTime1 ,DateTime2)).ToString );<br />
WriteLn('Number of weeks is '+ ( WeeksBetween( DateTime1 ,DateTime2)).ToString );<br />
ReadLn;<br />
end. <br />
<br />
</syntaxhighlight><br />
<br />
== Set Date ==<br />
<br />
Unit SysUtils function EncodeDate to set the date.<br />
<br />
<syntaxhighlight lang="pascal"><br />
function EncodeDate ( const Year, Month, Day : Word ) : TDateTime; <br />
</syntaxhighlight><br />
<br />
== Compare two TDateTime ==<br />
<br />
<br />
<syntaxhighlight lang="pascal"><br />
<br />
program CompareTwoDateTime;<br />
<br />
uses<br />
SysUtils, DateUtils;<br />
var<br />
firstDate, secondDate: TDateTime;<br />
begin<br />
firstDate := EncodeDate(2000, 2, 29);<br />
secondDate := EncodeDate(2018, 8, 11);<br />
if DaysBetween( firstDate, secondDate) = 0<br />
then WriteLn('Both dates are same')<br />
else<br />
if firstDate < secondDate<br />
then WriteLn('First date is earlier')<br />
else WriteLn('First date is later');<br />
ReadLn;<br />
end. <br />
</syntaxhighlight><br />
<br />
== See also ==<br />
<br />
* Date and time format [[ISO 8601]]<br />
* [[RFC 1123 Time Format]]<br />
* {{Doc|package=RTL|unit=sysutils|identifier=datetimeroutines|Date and time routines}} in the [[sysutils|<syntaxhighlight lang="pascal" inline>sysUtils</syntaxhighlight> unit]]</div>Mario13https://wiki.freepascal.org/index.php?title=TForm&diff=152517TForm2022-07-16T14:11:43Z<p>Mario13: /* Events */</p>
<hr />
<div>{{TForm}}<br />
<br />
'''TForm''' is the [[Class|class]] of a form object. All forms created at design time can be derived from TForm.<br />
<br />
The form represents a window or dialog box that forms the user interface of an [[Application|application]]. It is the container on which all other components (e.g. [[TButton|buttons]], [[TLabel|labels]], [[TEdit|edit fields]], [[TImage|images]]...) can be inserted.<br />
<br />
A new TForm can be created using [[IDE Window: New Item|File<nowiki>|</nowiki>new...]].<br />
<br />
== Application ==<br />
<br />
Forms created at design time using [[IDE Window: New Item|File<nowiki>|</nowiki>new...]] or clicking the new Form button, will create a new class or unit. To make one form accessable from another requires the new form to be added to the uses section of the unit for first form. To prevent circular referencing when each form requires to be added to the uses of the other, this will need to be added to a uses section under implementation.<br />
At program start, the main form and any other form that has to be 'autocreated' is actually instantiated. The forms are started in the sequence they are listed in the project. Autocreate forms may be selected from available forms in [Project|Project Options|Forms]. If for some reason available forms do not list the form that should be autocreated, add the necessary form name to the [[Program|program]]'s [[Uses|uses]] clause and add a line <tt>Application.CreateForm</tt> for that form.<br />
<br />
The project source code PTest.lpr: <br />
<br />
<syntaxhighlight lang=pascal><br />
program PTest;<br />
uses<br />
Forms,<br />
UMainForm,<br />
UOtherForm;<br />
{$R *.res}<br />
<br />
begin<br />
Application.Title:='Test';<br />
RequireDerivedFormResource := True;<br />
Application.Initialize();<br />
Application.CreateForm(TMainForm, MainForm);<br />
Application.CreateForm(TOtherForm, OtherForm);<br />
Application.Run();<br />
end. <br />
</syntaxhighlight><br />
<br />
== Properties ==<br />
<br />
* [[Action]], [[ActiveControl]], [[Align]], [[AllowDropFiles]], [[AlphaBlend]], [[AlphaBlendValue]], [[Anchors]], [[AutoScroll]], [[AutoSize]], [[BiDiMode]], [[BorderIcons]], [[BorderStyle]], [[BorderWidth]], [[Caption]], [[ChildSizing]], [[Color]], [[Constraints]], [[Cursor]], [[DefaultMonitor]], [[DesignTimePPI]], [[DockSite]], [[DragKind]], [[DragMode]], [[Enabled]], [[Font]], [[FormStyle]], [[Height]], [[HelpKeyword]], [[HelpType]], [[Hint]], [[HorzScrollBar]], [[Icon]], [[KeyPreview]], [[Left]], [[Menu]], [[Name]], [[ParentBiDiMode]], [[ParentFont]], [[PixelsPerInch]], [[PopupMenu]], [[PopupMode]], [[PopupParent]], [[Position]], [[Scaled]], [[SessionProperties]], [[ShowHint]], [[ShowInTaskBar]], [[Tag]], [[Top]], [[UseDockManager]], [[VertScrollBar]], [[Visible]], [[Width]], [[WindowState]]<br />
<br />
== Events ==<br />
<br />
* [[Action]], [[ActiveControl]], [[Constraints]], [[Menu]], [[OnActivate]], [[OnChangeBounds]], [[OnClick]], [[OnClose]], [[OnCloseQuery]], [[OnConstrainedResize]], [[OnContextPopup]], [[TForm.OnCreate | OnCreate]], [[OnDblClick]], [[OnDeactivate]], [[TForm.OnDestroy | OnDestroy]], [[OnDockDrop]], [[OnDockOver]], [[OnDragDrop]], [[OnDragOver]], [[OnDropFiles]], [[OnEndDock]], [[OnGetSiteInfo]], [[OnHelp]], [[OnHide]], [[key down | OnKeyDown]], [[OnKeyPress]], [[OnKeyUp]], [[OnMouseDown]], [[OnMouseEnter]], [[OnMouseLeave]], [[OnMouseUp]], [[OnMouseWheel]], [[OnMouseWheelDown]], [[OnMouseWheelUp]], [[OnPaint]], [[OnResize]], [[OnShortCut]], [[OnShow]], [[OnShowHint]], [[OnStratDock]], [[OnUnDock]], [[OnUTF8KeyPress]], [[OnWindowStateChange]], [[PopupMenu]], [[PopupParent]]<br />
<br />
== See also ==<br />
<br />
* [[doc:lcl/forms/tform.html|TForm doc]]<br />
* [[Form Tutorial]]</div>Mario13https://wiki.freepascal.org/index.php?title=TForm.OnDestroy&diff=152516TForm.OnDestroy2022-07-16T12:44:02Z<p>Mario13: </p>
<hr />
<div>== Overview ==<br />
<br />
The '''OnDestroy''' event is used to perform special processing when the form is destroyed.<br />
<br />
Note that you can either implement this event or override the destructor of the form; but do not do both.<br />
<br />
This event should destroy any objects created in the OnCreate event.</div>Mario13https://wiki.freepascal.org/index.php?title=TForm.OnCreate&diff=152515TForm.OnCreate2022-07-16T12:43:46Z<p>Mario13: </p>
<hr />
<div>== Overview ==<br />
<br />
The '''OnCreate''' event is used to perform special processing when the form is created and is invoked by TCustomForm's constructor.<br />
<br />
Note that you can either implement this event or override the constructor of the form; but do not do both.<br />
<br />
Any objects created in the OnCreate event should be freed by the OnDestroy event.</div>Mario13https://wiki.freepascal.org/index.php?title=TForm.OnDestroy&diff=152514TForm.OnDestroy2022-07-16T12:43:12Z<p>Mario13: Created page with "== Overview == The '''OnDestroy''' event is used to perform special processing when the form is destroyed. Note that you can either implement this event or override the dest..."</p>
<hr />
<div>== Overview ==<br />
<br />
The '''OnDestroy''' event is used to perform special processing when the form is destroyed.<br />
<br />
Note that you can either implement this event or override the destructor of the form; but do not do both.<br />
This event should destroy any objects created in the OnCreate event.</div>Mario13https://wiki.freepascal.org/index.php?title=TForm.OnCreate&diff=152513TForm.OnCreate2022-07-16T12:39:54Z<p>Mario13: Created page with "== Overview == The '''OnCreate''' event is used to perform special processing when the form is created and is invoked by TCustomForm's constructor. Note that you can either..."</p>
<hr />
<div>== Overview ==<br />
<br />
The '''OnCreate''' event is used to perform special processing when the form is created and is invoked by TCustomForm's constructor.<br />
<br />
Note that you can either implement this event or override the constructor of the form; but do not do both.<br />
Any objects created in the OnCreate event should be freed by the OnDestroy event.</div>Mario13https://wiki.freepascal.org/index.php?title=TForm&diff=152512TForm2022-07-16T12:39:07Z<p>Mario13: /* Events */</p>
<hr />
<div>{{TForm}}<br />
<br />
'''TForm''' is the [[Class|class]] of a form object. All forms created at design time can be derived from TForm.<br />
<br />
The form represents a window or dialog box that forms the user interface of an [[Application|application]]. It is the container on which all other components (e.g. [[TButton|buttons]], [[TLabel|labels]], [[TEdit|edit fields]], [[TImage|images]]...) can be inserted.<br />
<br />
A new TForm can be created using [[IDE Window: New Item|File<nowiki>|</nowiki>new...]].<br />
<br />
== Application ==<br />
<br />
Forms created at design time using [[IDE Window: New Item|File<nowiki>|</nowiki>new...]] or clicking the new Form button, will create a new class or unit. To make one form accessable from another requires the new form to be added to the uses section of the unit for first form. To prevent circular referencing when each form requires to be added to the uses of the other, this will need to be added to a uses section under implementation.<br />
At program start, the main form and any other form that has to be 'autocreated' is actually instantiated. The forms are started in the sequence they are listed in the project. Autocreate forms may be selected from available forms in [Project|Project Options|Forms]. If for some reason available forms do not list the form that should be autocreated, add the necessary form name to the [[Program|program]]'s [[Uses|uses]] clause and add a line <tt>Application.CreateForm</tt> for that form.<br />
<br />
The project source code PTest.lpr: <br />
<br />
<syntaxhighlight lang=pascal><br />
program PTest;<br />
uses<br />
Forms,<br />
UMainForm,<br />
UOtherForm;<br />
{$R *.res}<br />
<br />
begin<br />
Application.Title:='Test';<br />
RequireDerivedFormResource := True;<br />
Application.Initialize();<br />
Application.CreateForm(TMainForm, MainForm);<br />
Application.CreateForm(TOtherForm, OtherForm);<br />
Application.Run();<br />
end. <br />
</syntaxhighlight><br />
<br />
== Properties ==<br />
<br />
* [[Action]], [[ActiveControl]], [[Align]], [[AllowDropFiles]], [[AlphaBlend]], [[AlphaBlendValue]], [[Anchors]], [[AutoScroll]], [[AutoSize]], [[BiDiMode]], [[BorderIcons]], [[BorderStyle]], [[BorderWidth]], [[Caption]], [[ChildSizing]], [[Color]], [[Constraints]], [[Cursor]], [[DefaultMonitor]], [[DesignTimePPI]], [[DockSite]], [[DragKind]], [[DragMode]], [[Enabled]], [[Font]], [[FormStyle]], [[Height]], [[HelpKeyword]], [[HelpType]], [[Hint]], [[HorzScrollBar]], [[Icon]], [[KeyPreview]], [[Left]], [[Menu]], [[Name]], [[ParentBiDiMode]], [[ParentFont]], [[PixelsPerInch]], [[PopupMenu]], [[PopupMode]], [[PopupParent]], [[Position]], [[Scaled]], [[SessionProperties]], [[ShowHint]], [[ShowInTaskBar]], [[Tag]], [[Top]], [[UseDockManager]], [[VertScrollBar]], [[Visible]], [[Width]], [[WindowState]]<br />
<br />
== Events ==<br />
<br />
* [[Action]], [[ActiveControl]], [[Constraints]], [[Menu]], [[OnActivate]], [[OnChangeBounds]], [[OnClick]], [[OnClose]], [[OnCloseQuery]], [[OnConstrainedResize]], [[OnContextPopup]], [[TForm.OnCreate|OnCreate]], [[OnDblClick]], [[OnDeactivate]], [[TForm.OnDestroy|OnDestroy]], [[OnDockDrop]], [[OnDockOver]], [[OnDragDrop]], [[OnDragOver]], [[OnDropFiles]], [[OnEndDock]], [[OnGetSiteInfo]], [[OnHelp]], [[OnHide]], [[key down | OnKeyDown]], [[OnKeyPress]], [[OnKeyUp]], [[OnMouseDown]], [[OnMouseEnter]], [[OnMouseLeave]], [[OnMouseUp]], [[OnMouseWheel]], [[OnMouseWheelDown]], [[OnMouseWheelUp]], [[OnPaint]], [[OnResize]], [[OnShortCut]], [[OnShow]], [[OnShowHint]], [[OnStratDock]], [[OnUnDock]], [[OnUTF8KeyPress]], [[OnWindowStateChange]], [[PopupMenu]], [[PopupParent]]<br />
<br />
== See also ==<br />
<br />
* [[doc:lcl/forms/tform.html|TForm doc]]<br />
* [[Form Tutorial]]</div>Mario13https://wiki.freepascal.org/index.php?title=TForm&diff=152511TForm2022-07-16T12:37:00Z<p>Mario13: /* Events */</p>
<hr />
<div>{{TForm}}<br />
<br />
'''TForm''' is the [[Class|class]] of a form object. All forms created at design time can be derived from TForm.<br />
<br />
The form represents a window or dialog box that forms the user interface of an [[Application|application]]. It is the container on which all other components (e.g. [[TButton|buttons]], [[TLabel|labels]], [[TEdit|edit fields]], [[TImage|images]]...) can be inserted.<br />
<br />
A new TForm can be created using [[IDE Window: New Item|File<nowiki>|</nowiki>new...]].<br />
<br />
== Application ==<br />
<br />
Forms created at design time using [[IDE Window: New Item|File<nowiki>|</nowiki>new...]] or clicking the new Form button, will create a new class or unit. To make one form accessable from another requires the new form to be added to the uses section of the unit for first form. To prevent circular referencing when each form requires to be added to the uses of the other, this will need to be added to a uses section under implementation.<br />
At program start, the main form and any other form that has to be 'autocreated' is actually instantiated. The forms are started in the sequence they are listed in the project. Autocreate forms may be selected from available forms in [Project|Project Options|Forms]. If for some reason available forms do not list the form that should be autocreated, add the necessary form name to the [[Program|program]]'s [[Uses|uses]] clause and add a line <tt>Application.CreateForm</tt> for that form.<br />
<br />
The project source code PTest.lpr: <br />
<br />
<syntaxhighlight lang=pascal><br />
program PTest;<br />
uses<br />
Forms,<br />
UMainForm,<br />
UOtherForm;<br />
{$R *.res}<br />
<br />
begin<br />
Application.Title:='Test';<br />
RequireDerivedFormResource := True;<br />
Application.Initialize();<br />
Application.CreateForm(TMainForm, MainForm);<br />
Application.CreateForm(TOtherForm, OtherForm);<br />
Application.Run();<br />
end. <br />
</syntaxhighlight><br />
<br />
== Properties ==<br />
<br />
* [[Action]], [[ActiveControl]], [[Align]], [[AllowDropFiles]], [[AlphaBlend]], [[AlphaBlendValue]], [[Anchors]], [[AutoScroll]], [[AutoSize]], [[BiDiMode]], [[BorderIcons]], [[BorderStyle]], [[BorderWidth]], [[Caption]], [[ChildSizing]], [[Color]], [[Constraints]], [[Cursor]], [[DefaultMonitor]], [[DesignTimePPI]], [[DockSite]], [[DragKind]], [[DragMode]], [[Enabled]], [[Font]], [[FormStyle]], [[Height]], [[HelpKeyword]], [[HelpType]], [[Hint]], [[HorzScrollBar]], [[Icon]], [[KeyPreview]], [[Left]], [[Menu]], [[Name]], [[ParentBiDiMode]], [[ParentFont]], [[PixelsPerInch]], [[PopupMenu]], [[PopupMode]], [[PopupParent]], [[Position]], [[Scaled]], [[SessionProperties]], [[ShowHint]], [[ShowInTaskBar]], [[Tag]], [[Top]], [[UseDockManager]], [[VertScrollBar]], [[Visible]], [[Width]], [[WindowState]]<br />
<br />
== Events ==<br />
<br />
* [[Action]], [[ActiveControl]], [[Constraints]], [[Menu]], [[OnActivate]], [[OnChangeBounds]], [[OnClick]], [[OnClose]], [[OnCloseQuery]], [[OnConstrainedResize]], [[OnContextPopup]], [[TForm.OnCreate]], [[OnDblClick]], [[OnDeactivate]], [[TForm.OnDestroy]], [[OnDockDrop]], [[OnDockOver]], [[OnDragDrop]], [[OnDragOver]], [[OnDropFiles]], [[OnEndDock]], [[OnGetSiteInfo]], [[OnHelp]], [[OnHide]], [[key down | OnKeyDown]], [[OnKeyPress]], [[OnKeyUp]], [[OnMouseDown]], [[OnMouseEnter]], [[OnMouseLeave]], [[OnMouseUp]], [[OnMouseWheel]], [[OnMouseWheelDown]], [[OnMouseWheelUp]], [[OnPaint]], [[OnResize]], [[OnShortCut]], [[OnShow]], [[OnShowHint]], [[OnStratDock]], [[OnUnDock]], [[OnUTF8KeyPress]], [[OnWindowStateChange]], [[PopupMenu]], [[PopupParent]]<br />
<br />
== See also ==<br />
<br />
* [[doc:lcl/forms/tform.html|TForm doc]]<br />
* [[Form Tutorial]]</div>Mario13https://wiki.freepascal.org/index.php?title=OnCreate&diff=152510OnCreate2022-07-16T12:34:46Z<p>Mario13: Created page with "== Overview == The '''OnCreate''' event is used to perform special processing when the form is created and is invoked by TCustomForm's constructor. Note that you can either..."</p>
<hr />
<div>== Overview ==<br />
<br />
The '''OnCreate''' event is used to perform special processing when the form is created and is invoked by TCustomForm's constructor.<br />
<br />
Note that you can either implement this event or override the constructor of the form; but do not do both.<br />
Any objects created in the OnCreate event should be freed by the OnDestroy event.</div>Mario13https://wiki.freepascal.org/index.php?title=Lazarus_Components&diff=116847Lazarus Components2018-04-04T14:34:38Z<p>Mario13: </p>
<hr />
<div>This is an overview of the components included in Lazarus and a comparison to those included with TurboDelphi (from 2006)<br />
<br />
{| class="wikitable"<br />
! Component !! Turbo Delphi !! Lazarus !! Notes<br />
|- style="background-color:#cccccc;"<br />
|colspan="4"|<br />
STANDARD<br />
|-<br />
|[[TActionList]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TButton]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TCheckBox]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TComboBox]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TEdit]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TFrame]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TGroupBox]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TLabel]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TListBox]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TMainMenu]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TMemo]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TPanel]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TPopupMenu]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TRadioButton]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TRadioGroup]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TScrollBar]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TToggleBox]]<br />
|<br />
|x<br />
|<br />
|- style="background-color:#cccccc;"<br />
|colspan="4"|<br />
|-<br />
! Component !! Turbo Delphi !! Lazarus !! Notes<br />
|- style="background-color:#cccccc;"<br />
|colspan="4"|<br />
ADDITIONAL<br />
|-<br />
|[[TActionManager]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TActionMainMenuBar]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TActionToolBar]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TApplicationEvents]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TApplicationProperties]]<br />
|<br />
|x<br />
|<br />
|-<br />
|[[TBevel]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TBitBtn]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TButtonGroup]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TCategoryButtons]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TChart]]<br />
|x*<br />
|x**<br />
| [[TAChart]]<br />
|-<br />
|TCheckListBox<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TColorBox]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TColorListBox]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TControlBar]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TCustomizeDlg]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TDockTabSet]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TDrawGrid]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TFlowPanel]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TGridPanel]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TImage]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TLabeledEdit]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TMaskEdit]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TPopupActionBar]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TScrollBox]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TShape]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TSpeedButton]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TSplitter]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TStandardColorMap]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TStaticText]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TStringGrid]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TTabSet]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TTrayIcon]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TTwilightColorMap]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TValueListEditor]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TXPColorMap]]<br />
|x<br />
|<br />
|<br />
|-<br />
|-<br />
|[[TPairSplitter]]<br />
|x<br />
|x<br />
|<br />
|- style="background-color:#cccccc;"<br />
|colspan="4"|<br />
|-<br />
! Component !! Turbo Delphi !! Lazarus !! Notes<br />
|- style="background-color:#cccccc;"<br />
|colspan="4"|<br />
WIN 32\Common Controls<br />
|-<br />
|[[TAnimate]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TComboBoxEx]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TCoolBar]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TDateTimePicker]]<br />
|x<br />
|x<br />
|[[DateTimeCtrls_Package]]<br />
|-<br />
|[[THeaderControl]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[THotKey]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TImageList]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TListView]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TMonthCalendar]]<br />
|x<br />
|x*<br />
|[[TCalendar]]<br />
|-<br />
|[[TPageControl]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TPageScroller]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TPopupNotifier]]<br />
|<br />
|x<br />
|-<br />
|[[TProgressBar]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TRichEdit]]<br />
|x<br />
|x*<br />
| [[RichView]],[[RichMemo]]<br />
|-<br />
|[[TStatusBar]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TTabControl]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TTrackBar]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TToolBar]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TTreeView]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TUpDown]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TXPManifest]]<br />
|x<br />
|x*<br />
|<br />
|- style="background-color:#cccccc;"<br />
|colspan="4"|<br />
|-<br />
! Component !! Turbo Delphi !! Lazarus !! Notes<br />
|- style="background-color:#cccccc;"<br />
|colspan="4"|<br />
SYSTEM<br />
|-<br />
|[[TPaintBox]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TTimer]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TMediaPlayer]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TOleContainer]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TCOMAdminCatalog]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TDDEClientConv]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TDDEClientItem]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TDDEServerConv]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TDDEServerItem]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TIdleTimer]]<br />
|<br />
|x<br />
|<br />
|-<br />
|[[TLazComponentQueue]]<br />
|<br />
|x<br />
|<br />
|-<br />
|[[THTMLHelpDatabase]]<br />
|<br />
|x<br />
|<br />
|-<br />
|[[THTMLBrowserHelpViewer]]<br />
|<br />
|x<br />
|<br />
|-<br />
|[[TProcessUTF8]]<br />
|<br />
|x<br />
|<br />
|-<br />
|[[TAsyncProcess]]<br />
|<br />
|x<br />
|<br />
<br />
|-<br />
|[[TProcess]]<br />
|<br />
|x<br />
|<br />
|-<br />
|[[TSimpleIPCClient]]<br />
|<br />
|x<br />
|<br />
|-<br />
|[[TSimpleIPCServer]]<br />
|<br />
|x<br />
|<br />
|-<br />
|[[TXMLConfig]]<br />
|<br />
|x<br />
|<br />
|-<br />
|[[TEventLog]]<br />
|<br />
|x<br />
|<br />
|- style="background-color:#cccccc;"<br />
|colspan="4"|<br />
|-<br />
! Component !! Turbo Delphi !! Lazarus !! Notes<br />
|- style="background-color:#cccccc;"<br />
|colspan="4"|<br />
WIN 3.1<br />
|-<br />
|[[TDBLookupList]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TDBLookupCombo]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TDirectoryListBox]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TDriveComboBox]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TFileListBox]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TDBLookupList]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TFilterComboBox]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TDBLookupList]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[THeader]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TOutline]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TNotebook]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TTabbedNotebook]]<br />
|x<br />
|<br />
|<br />
|- style="background-color:#cccccc;"<br />
|colspan="4"|<br />
|-<br />
! Component !! Turbo Delphi !! Lazarus !! Notes<br />
|- style="background-color:#cccccc;"<br />
|colspan="4"|<br />
DATA ACCESS<br />
|-<br />
|[[TClientDataSet]]<br />
|x<br />
|<br />
|try TBufDataSet (unit BufDataset)<br />
|-<br />
|[[TDataSetProvider]]<br />
|x<br />
|<br />
|try TDataSource (unit db)<br />
|-<br />
|[[TDataSource]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TXMLTransform]]<br />
|<br />
|<br />
|<br />
|-<br />
|[[TXMLTransformClient]]<br />
|<br />
|<br />
|<br />
|-<br />
|[[TXMLTransformProvider]]<br />
|<br />
|<br />
|<br />
|-<br />
|[[TDbf]]<br />
|<br />
|x<br />
|<br />
|-<br />
|[[TSdfDataSet]]<br />
|<br />
|x<br />
|<br />
|-<br />
|[[TFixedFormatDataSet]]<br />
|<br />
|x<br />
|<br />
|-<br />
|[[TMemDataset]]<br />
|<br />
|x<br />
|<br />
|- style="background-color:#cccccc;"<br />
|colspan="4"|<br />
|-<br />
! Component !! Turbo Delphi !! Lazarus !! Notes<br />
|- style="background-color:#cccccc;"<br />
|colspan="4"|<br />
DATA CONTROLS<br />
|-<br />
|[[TDBChart]]<br />
|x*<br />
|<br />
|<br />
|-<br />
|[[TDBCheckBox]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TDBComboBox]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TDBCtrlGrid]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TDBEdit]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TDBGrid]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TDBImage]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TDBListBox]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TDBLookupComboBox]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TDBLookupListBox]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TDBMemo]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TDBNavigator]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TDBRadioGroup]]<br />
|x<br />
|x<br />
|<br />
|-<br />
|[[TDBRichEdit]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TDBText]]<br />
|x<br />
|x<br />
|<br />
|- style="background-color:#cccccc;"<br />
|colspan="4"|<br />
|-<br />
! Component !! Turbo Delphi !! Lazarus !! Notes<br />
|- style="background-color:#cccccc;"<br />
|colspan="4"|<br />
ADO\dbGo<br />
|-<br />
|[[TADOConnection]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TADOCommand]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TADODataSet]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TADOTable]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TADOQuery]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TADOStoredProc]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TRDSConnection]]<br />
|x<br />
|<br />
|<br />
|- style="background-color:#cccccc;"<br />
|colspan="4"|<br />
|-<br />
! Component !! Turbo Delphi !! Lazarus !! Notes<br />
|- style="background-color:#cccccc;"<br />
|colspan="4"|<br />
BDE<br />
|-<br />
|[[TTable]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TQuery]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TStoredProc]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TDatabase]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TSession]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TBatchMove]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TUpdateSQL]]<br />
|x<br />
|<br />
|<br />
|- style="background-color:#cccccc;"<br />
|colspan="4"|<br />
|-<br />
! Component !! Turbo Delphi !! Lazarus !! Notes<br />
|- style="background-color:#cccccc;"<br />
|colspan="4"|<br />
INTERBASE<br />
|-<br />
| [[TIBQuery]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TIBDatabase]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TIBTransaction]]<br />
|]<br />
|x<br />
|<br />
|- style="background-color:#cccccc;"<br />
|colspan="4"|<br />
|-<br />
! Component !! Turbo Delphi !! Lazarus !! Notes<br />
|- style="background-color:#cccccc;"<br />
|colspan="4"|<br />
DBEXPRESS\SQLdb<br />
|-<br />
| [[TSQLConnection]]<br />
|x<br />
|x*<br />
|<br />
|-<br />
| [[TSQLDataSet]]<br />
|x<br />
|<br />
|<br />
|-<br />
| [[TSQLQuery]]<br />
|x<br />
|x<br />
|<br />
|-<br />
| [[TSQLStoredProc]]<br />
|x<br />
|<br />
|<br />
|-<br />
| [[TSQLTable]]<br />
|x<br />
|<br />
|<br />
|-<br />
| [[TSQLMonitor]]<br />
|<br />
|<br />
|<br />
|-<br />
| [[TSimpleDataSet]]<br />
|x<br />
|<br />
|<br />
|-<br />
| [[TSQLTransaction]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TSQLScript]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TSQLConnector]]<br />
|<br />
|x<br />
|- style="background-color:#cccccc;"<br />
|colspan="4"|<br />
|-<br />
! Component !! Turbo Delphi !! Lazarus !! Notes<br />
|- style="background-color:#cccccc;"<br />
|colspan="4"|<br />
WEBSERVICES [[Web_Service_Toolkit]]<br />
|-<br />
| [[THTTPRIO]]<br />
|x<br />
|<br />
|<br />
|-<br />
| [[THTTPReqResp]]<br />
|x<br />
|<br />
|<br />
|-<br />
| [[TOPToSoapDomConvert]]<br />
|x<br />
|<br />
|<br />
|-<br />
|[[TSOAPConnection]]<br />
|x<br />
|<br />
|<br />
|-<br />
| [[THTTPSoapDispatcher]]<br />
|x<br />
|<br />
|<br />
|-<br />
| [[TWSDLHTMLPublish]]<br />
|x<br />
|<br />
|<br />
|-<br />
| [[THTTPSoapPascalInvoker]]<br />
|x<br />
|<br />
|<br />
|-<br />
| [[THTTPSoapCppInvoker]]<br />
|x<br />
|<br />
|<br />
|- style="background-color:#cccccc;"<br />
|colspan="4"|<br />
|-<br />
! Component !! Turbo Delphi !! Lazarus !! Notes<br />
|- style="background-color:#cccccc;"<br />
|colspan="4"|<br />
INTERNET<br />
|-<br />
| [[TWebDispatcher]]<br />
|x<br />
|<br />
|<br />
|-<br />
| [[TPageProducer]]<br />
|x<br />
|<br />
|<br />
|-<br />
| [[TDataSetTableProducer]]<br />
|x<br />
|<br />
|<br />
|-<br />
| [[TDataSetPageProducer]]<br />
|x<br />
|<br />
|<br />
|-<br />
| [[TQueryTableProducer]]<br />
|x<br />
|<br />
|<br />
|-<br />
| [[TSQLQueryTableProducer]]<br />
|x<br />
|<br />
|<br />
|-<br />
| [[TTCPClient]]<br />
|x<br />
|<br />
|<br />
|-<br />
| [[TTCPServer]]<br />
|x<br />
|<br />
|<br />
|-<br />
| [[TUDPSocket]]<br />
|x<br />
|<br />
|<br />
|-<br />
| [[TXMLDocument]]<br />
|x<br />
|<br />
|<br />
|-<br />
| [[TWebBrowser]]<br />
|x<br />
|x*<br />
| [[IPro]]<br />
|- style="background-color:#cccccc;"<br />
|colspan="4"|<br />
|-<br />
! Component !! Turbo Delphi !! Lazarus !! Notes<br />
|- style="background-color:#cccccc;"<br />
|colspan="4"|<br />
DIALOGS<br />
|-<br />
| [[TCalendarDialog]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TCalculatorDialog]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TColorDialog]]<br />
|x<br />
|x<br />
|<br />
|-<br />
| [[TFolderBrowserDialog]]<br />
|x*<br />
|x**<br />
|*available via function.** [[TSelectDirectoryDialog]]<br />
|-<br />
| [[TFindDialog]]<br />
|x<br />
|x<br />
|<br />
|-<br />
| [[TFontDialog]]<br />
|x<br />
|x<br />
|<br />
|-<br />
| [[TOpenDialog]]<br />
|x<br />
|x<br />
|<br />
|-<br />
| [[TOpenPictureDialog]]<br />
|x<br />
|x<br />
|<br />
|-<br />
| [[TOpenTextFileDialog]]<br />
|x<br />
|<br />
|<br />
|-<br />
| [[TPageSetupDialog]]<br />
|x<br />
|x<br />
|<br />
|-<br />
| [[TPrintDialog]]<br />
|x<br />
|x<br />
|<br />
|-<br />
| [[TPrinterSetupDialog]]<br />
|x<br />
|x<br />
|<br />
|-<br />
| [[TReplaceDialog]]<br />
|x<br />
|x<br />
|<br />
|-<br />
| [[TSaveDialog]]<br />
|x<br />
|x<br />
|<br />
|-<br />
| [[TSavePictureDialog]]<br />
|x<br />
|x<br />
|<br />
|-<br />
| [[TSaveTextFileDialog]]<br />
|x<br />
|<br />
|<br />
|- style="background-color:#cccccc;"<br />
|colspan="4"|<br />
|-<br />
! Component !! Turbo Delphi !! Lazarus !! Notes<br />
|- style="background-color:#cccccc;"<br />
|colspan="4"|<br />
SAMPLES<br />
|-<br />
| [[TSpinButton]]<br />
|x<br />
|<br />
|<br />
|-<br />
| [[TSpinEdit]]<br />
|x<br />
|x<br />
|<br />
|-<br />
| [[TDirectoryOutline]]<br />
|x<br />
|<br />
|<br />
|-<br />
| [[TCalendar]]<br />
|x<br />
|x<br />
|<br />
|-<br />
| [[IBEventAlerter]]<br />
|x<br />
|<br />
|<br />
|-<br />
| [[TShellTreeView]]<br />
|x<br />
|x<br />
|Shell_Controls<br />
|-<br />
|[[TShellComboBox]]<br />
|x<br />
|<br />
|<br />
|-<br />
| [[TShellListView]]<br />
|x<br />
|x<br />
|Shell_Controls<br />
|-<br />
| [[TShellChangeNotifier]]<br />
|x<br />
|<br />
|<br />
|-<br />
| [[TColorGrid]]<br />
|x<br />
|<br />
|<br />
|-<br />
| [[TGauge]]<br />
|x<br />
|<br />
|<br />
|- style="background-color:#cccccc;"<br />
|colspan="4"|<br />
|-<br />
! Component !! Turbo Delphi !! Lazarus !! Notes<br />
|- style="background-color:#cccccc;"<br />
|colspan="4"|<br />
MISC<br />
|-<br />
| [[TColorButton]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TFloatSpinEdit]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TArrow]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TCalendar]]<br />
|x*<br />
|x<br />
|<br />
|-<br />
| [[TEditButton]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TFileNameEdit]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TDirectoryEdit]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TDateEdit]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TCalcEdit]]<br />
|<br />
|x<br />
|<br />
<br />
|-<br />
| [[TFileListBox]]<br />
|x<br />
|x<br />
|<br />
|-<br />
| [[TXMLPropStorage]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TINIPropStorage]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TBarChart]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TButtonPanel]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TIDEDialogLayoutStorage]]<br />
|<br />
|x<br />
|<br />
|- style="background-color:#cccccc;"<br />
|colspan="4"|<br />
|-<br />
! Component !! Turbo Delphi !! Lazarus !! Notes<br />
|- style="background-color:#cccccc;"<br />
|colspan="4"|<br />
RTTI<br />
|-<br />
| [[TTIButton]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TTICalendar]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TTICheckBox]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TTICheckGroup]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TTICheckListBox]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TTIColorButton]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TTIComboBox]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TTIEdit]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TTIFloatSpinEdit]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TTIGrid]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TTIGroupBox]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TTIImage]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TTILabel]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TTIListBox]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TTIMaskEdit]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TTIMemo]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TMultiPropertyLink]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TTIProgressBar]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TTIPropertyGrid]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TTIRadioGroup]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TTISpinEdit]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TTITrackBar]]<br />
|<br />
|x<br />
|<br />
|- style="background-color:#cccccc;"<br />
|colspan="4"|<br />
|-<br />
! Component !! Turbo Delphi !! Lazarus !! Notes<br />
|- style="background-color:#cccccc;"<br />
|colspan="4"|<br />
SynEdit<br />
|-<br />
| [[TSynEdit]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TSynAutoComplete]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TSynExporterHTML]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TSynMacroRecorder]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TSynMemo]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TSynPasSyn]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TSynFreePascalSyn]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TSynCppSyn]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TSynJavaSyn]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TSynPerlSyn]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TSynHTMLSyn]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TSynXMLSyn]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TSynLFMSyn]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TSynUNIXShellScriptSyn]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TSynCssSyn]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TSynPHPSyn]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TSynTeXSyn]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TSynSQLSyn]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TSynPythonSyn]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TSynVBSyn]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TSynAnySyn]]<br />
|<br />
|x<br />
|<br />
|-<br />
| [[TSynMultiSyn]]<br />
|<br />
|x<br />
|<br />
|- style="background-color:#cccccc;"<br />
|colspan="4"|<br />
INDY<br />
|-<br />
|...<br />
|x*<br />
|x*<br />
|http://www.indyproject.org<br />
|-<br />
|}<br />
<br />
[[Category:Lazarus]]<br />
[[Category:Components]]</div>Mario13https://wiki.freepascal.org/index.php?title=User:Mario13&diff=116763User:Mario132018-03-29T14:26:16Z<p>Mario13: Created page with "Hi, my name is Mario Guerra, from Argentina."</p>
<hr />
<div>Hi, my name is Mario Guerra, from Argentina.</div>Mario13https://wiki.freepascal.org/index.php?title=LazReport_Documentation&diff=116762LazReport Documentation2018-03-29T14:22:44Z<p>Mario13: /* Logical/boolean functions */</p>
<hr />
<div>{{LazReport Documentation}}<br />
<br />
=Overview=<br />
LazReport is a group of components to add reporting capabilities to applications. It uses a visual designer to create banded reports and includes a report engine with previewer and an interpreter to run user scripts. The report designer can<br />
be invoked at runtime. <br />
<br />
=License=<br />
LazReport is based on FreeReport 2.32 and thanks to Fast Reports Inc. it's available under modified LGPL, the same license as the Lazarus LCL.<br />
See files lazreport/license.txt, license-rus.txt and license-lazreport.txt for details.<br />
<br />
=Authors=<br />
FreeReport was created for Fast Reports Inc.<br />
<br />
LazReport initial port was made by Olivier Guilbaud.<br />
<br />
Lazarus integration and fixes by Jesus Reyes A.<br />
<br />
Many contributors, see lazreport/doc/contributors.txt file<br />
<br />
=Install=<br />
To install LazReport in the Lazarus IDE:<br />
<br />
# Open LazReport Package. Menu: Components->Open package file (.lpk)...<br />
# Open file components/lazreport/source/lazreport.lpk<br />
# Install<br />
<br />
The next time Lazarus is started, it should show a LazReport tab in the component palette.<br />
<br />
=Documentation=<br />
Developer's manual and User Guides specific for LazReport are yet to be written. In the mean time, most LazReport features are described in the FreeReport Developer's Manual (see lazreport/doc/fr_eng.sxw in your Lazarus installation). Platform specific things described there like OLE objects are not implemented in LazReport, also some examples or pictures make reference to samples available only on Delphi. <br />
<br />
Until LazReport documentation is elaborated, this Wiki page will be used as a documentation container; maybe in the future the missing documentation could be generated from here. Users are welcomed to add topics that they feel need to be documented.<br />
<br />
==Operators==<br />
The following operators are supported:<br />
{| BORDER="1" CELLSPACING="0"<br />
!COLSPAN="1" STYLE="background:#ffdead;"|Operator type<br />
!COLSPAN="1" STYLE="background:#ffdead;"|Operators<br />
|---- <br />
|Logical||>, <, BUT, AND, NOT, =, < >, > =, < = <br />
|---- <br />
|Mathematical||-, *, +, MOD, /<br />
|}<br />
<br />
==Functions==<br />
The following functions are available for use:<br />
===Statistical functions===<br />
<br />
;SUM(<X >) : Returns the sum of values represented by <X>, which is generally a data field. <br />
;AVG(<X >) : Returns the average of <X> values.<br />
;COUNT : Count the number of occurrences.<br />
;MIN(<X >) : Returns the lowest value of all values represented by <X><br />
;MAX(<X >) : Returns the highest value of all values represented by <X><br />
<br />
===Date functions===<br />
{{Note|December 2013: inspection of lr_pars source code seems to indicate these functions work with the current locale date format, which limits interoperability. To do: verify this; extend function with an extra format parameter which defaults to e.g. ISO8601}}<br />
<br />
;FORMATDATETIME(<X>, <Y >) : Returns <Y> TDateTime in format <X>. <X> uses the default syntax for [http://www.freepascal.org/docs-html/rtl/sysutils/formatdatetime.html Lazarus formats].<br />
;FORMATFLOAT(<X>, <Y >) : Returns the numeric value <Y> in format <X>. <<X> uses the default syntax for [http://www.freepascal.org/docs-html/rtl/sysutils/formatfloat.html Lazarus formats].<br />
;STRTODATE(<X >) : Returns the TDateTime(? not date?) representation of string < X >. < X > must be formatted correctly.<br />
;STRTOTIME(<X >) : Returns the TDateTime time part representation of string < X >. < X > must be formatted correctly.<br />
<br />
===String functions:===<br />
;LOWERCASE(<X >) : Returns lowercase <X><br />
;UPPERCASE(<X >) : Returns uppercase <X><br />
;NAMECASE(<X >) : Returns <X> with initial capitals<br />
;COPY(<X>, <Y>, <Z >) : Similar to Pascal Copy: returns string <X> from position < Y > for < Z > characters. <br />
<br />
===Numeric functions===<br />
;FRAC(<X >) : Returns the decimal part of number < X ><br />
;INT(<X >) : Returns the integer part of number < X ><br />
;ROUND(<X >) : Returns the number < X > rounded to an integer (up? down? nearest integer? banker's rounding?)<br />
;STR(<X >) : Returns the string representation of number < X ><br />
<br />
===Logical/boolean functions===<br />
;IF(<X>, <Y>, <Z>) : Returns < Y > if expression < X > is true. If false, returns < Z >.<br />
<br />
==Adding your own functions==<br />
Though it is probably not needed much, LazReport allows you to define your own functions. As mentioned, see [[LazReport Documentation#Documentation]] for an overview of existing functions.<br />
<br />
To add your own functions:<br />
<br />
=== Add template to definition file ===<br />
{{Note|This was taken from the Delphi/FastReport/FreeReport tutorial in Portuguese. It should be verified and probably modified to work with current Lazarus/LazReport}}<br />
<br />
You need to define your functions following the following template in the file FR.lng ('''is this still the correct name for Lazreprot?'''):<br />
<br />
, FCT = CATEGORY|FCT (<X> <Y>, <z>)|Help<br />
<br />
where:<br />
* FCT is the function name. <br />
* CATEGORY is the category name. <br />
* FCT (<X> <Y>, <z>), is the layout of the required parameters, with a maximum of 3 parameters. <br />
* Help Is a small help text which should allow the user to understand the purpose of the function. <br />
* | is a separator.<br />
<br />
Each parameter is separated by commas and can be an expression, a constant, a variable, a field or data.<br />
Alphanumeric type constants should be limited by a character. The variables are delimited by '''and'''.<br />
<br />
Data fields are limited to the variables and have the following format:<br />
;Dataset_Name. "Field_Name" <br />
<br />
Let's add the SQRT and POS functions by adding the following lines to '''FR.lng''' todo: still the same name?<br />
;SQRT = Mathematics and Trigonometry|SQRT(<X>)|Returns the square root of <X> <br />
;POS = Strings|POS(<X>,<Y>) Returns the position of string <X> within string <Y><br />
<br />
=== Add function source code ===<br />
A function definition is nice, but we haven't specified how these functions work. Therefore, some source code to add the functions POS and SQRT below:<br />
<syntaxhighlight><br />
Unit FR_OGFct;<br />
interface <br />
implementation <br />
uses FR_Pars, FR_Class; // Standard declarations needed for Lazreport!! Note: FR_pars etc? Are these names ok?<br />
type <br />
// Our own functions are declared here.<br />
TfrOGFunctionLibrary = class(TfrFunctionLibrary)<br />
public <br />
constructor Create; override; <br />
procedure DoFunction(FNo:integer procedure; p1, p2,<br />
p3:Variant; var valley:string); override; <br />
p3:Variant; var valley:string);<br />
end; <br />
//************************** <br />
// * TfrOGFunctionLibrary <br />
constructor TfrOGFunctionLibrary.Create;<br />
begin <br />
inherited Create; <br />
// Add our functions to the list of available functions:<br />
with List do <br />
begin<br />
Add('POS');<br />
Add('SQRT');<br />
end;<br />
end;<br />
<br />
Procedure TfrOGFunctionLibrary.DoFunction(FNo:Integer procedure; p1,<br />
p2, p3:Variant; Var valley:String); //valley?<br />
Var <br />
Par1, Par2: Varying;<br />
Result: Variantying; //variantying? variant?<br />
begin<br />
Try<br />
Case FNo of //this is the index of the functions as added in the constructor<br />
0 : <br />
begin // POS function<br />
Par1:=VarToStr(Parser.Calc(p1)); <br />
Par2:=VarToStr(Parser.Calc(P2)); <br />
Result:=Pos(Par1,Par2);<br />
end;<br />
1 : // SQRT function<br />
Result:=SQRT(Parser.Calc(P1));<br />
end;<br />
Except <br />
// String with error details<br />
Result:='Error in function '+List.Strings[FNo];<br />
end;<br />
Val:=VarToStr(Result); // Resulting string<br />
end;<br />
<br />
Procedure DoInit;<br />
begin<br />
frRegisterFunctionLibrary(TfrOGFunctionLibrary);<br />
end;<br />
</syntaxhighlight><br />
<br />
Save the report then File>List and this window will appear:<br />
<br />
[[Image:imagem21.jpg]]<br />
<br />
You may notice the appearance of a small (...) button, active only in the case of an expression. Click below to open the editor:<br />
<br />
[[Image:imagem22.jpg]]<br />
<br />
You may notice the similarity. If you click the Add button it will load the editor parameters:<br />
<br />
[[Image:imagem23.jpg]]<br />
<br />
Depending on the number of parameters, you have more or less edit areas. The (...) button makes it possible to open the expression generator to set the parameter.<br />
<br />
==Export Filters==<br />
LazReport has the ability to save the report displayed in the preview window using a user-defined format. It has an extension mechanism with support for plugins that can be used to add any amount of export filters. <br />
<br />
An export filter is a specially designed class which is registered in LazReport and allows you to save the report using one or more formats.<br />
<br />
When LazReport is installed, it includes some filters ready for use, these are: TfrTextExportFilter for exporting report as plain text, TfrCSVExportFilter used for exporting the report as CSV format and TfrHTMExportFilter for exporting the report as simple html file. Also included are some packages that provide additional filters, these are (see Menu Packages-> Install/De-Install packages...): lrCairoExport.lpk which provides support for exporting to PDF and PS formats by using the Cairo Graphics Library and lrExtExp.lpk with support for improved html export and some image formats like BMP, JPG and PNG. Also included in LazReport is the LazReportPDFExport.lpk package, this package provides PDF export using PowerPDF which is available in Lazarus-CCR repository.<br />
<br />
A filters package is installed in the same way as any other Lazarus Package; after restarting Lazarus, the filters (usually) appear as icons in the LazReport tab on the Component Palette.<br />
<br />
An export filter is added to your application by simply dragging one of these icons to a form or data module where TfrReport component exists, this is automatically registered and remains ready to use.<br />
<br />
This can also be done manually by including the export filter unit name in the Uses clause of the unit where TfrReport is used.<br />
<br />
LazReport export filters are invoked using one of two ways:<br />
#Save the report in the preview window. Using this method (pressing the save button) when the Save As dialog is presented, the user can choose a format from the list of registered formats. The list is populated by all registered export filters.<br />
#Through code using the TfrReport ExportTo method. See below for an example:<br />
<source><br />
if TheReport.PrepareReport then<br />
TheReport.ExportTo(TfrHTMExportFilter, 'exportedfile.html');<br />
</source><br />
Where TheReport holds an instance of TfrReport component. In this sample a TfrHTMExportFilter is used to generate a file named 'exportedfile.html'. It's not necessary to prepare the report again if it has been prepared previously.<br />
<br />
In order to use TfrHTMExportFilter the developer has to drag and drop an instance of the TfrHTMExportFilter component from the LazReport tab in the component palette to the form in the Form Designer. As an alternative the unit '''lr_e_htm.pas''' file can be added to the unit uses clause.<br />
<br />
Since LazReport 0.9.6, export filters support has been enhanced: now export filters can take parameters which users can customize either by changing values directly or by presenting the end user some UI. In order to make changes in parameters, the developer can create an event handler for TfrReport.OnExportFilterSetup event, available by selecting the TfrReport component and selecting the Events tab in Object Inspector.<br />
<br />
The OnExportFilterSetup (of type TExportFilterSetup) event handler takes an argument sender of type TfrExportFilter, in order to use this type, the '''lr_class.pas''' unit must be added to the unit uses clause. All ExportFilter clases share this event and the developer has to type-cast the sender argument to the desired export filter class, for example:<br />
<source><br />
if sender is TfrHTMExportFilter then<br />
begin<br />
TfrHTMExportFilter(sender).UseCSS := false;<br />
end;<br />
</source><br />
<br />
Below a description of available export filters.<br />
<br />
===TfrExportFilter=== <br />
is the base class of all export filters, and defines two properties that can be modified by the developer in the OnExportFilterSetup event:<br />
*'''BandTypes''': TfrBandTypes. this is a set of band types, only bands included in this set are actually exported; the other bands on the report will be ignored. Using this property a developer could for example export only the master band content, leaving titles, headers and footers out of exported output by doing:<br />
<source><br />
sender.BandTypes := [btMasterData];<br />
</source><br />
By default, all bands are processed but TfrCSVExportFilter changes this property to process only master header, column header and master data bands.<br />
*'''UseProgressbar''': boolean. This property enables or disables showing the progress bar while processing the export filter. This property is false by default.<br />
===TfrTextExportFilter===<br />
inheritance: TfrExportFilter <- TfrTextExportFilter<br>located in: '''lr_e_txt.pas''' file included with the LazReport package.<br />
<br />
is the base class of text based export filters. This export filter tries to make a text representation of a graphical report by fitting the original graphical coordinates into a more coarse grid where each unit is of "UsedFont" pixels, depending on the value of UsedFont value, the exported output may more or less represent the layout of objects in graphical report. Beside the properties inherited from TfrExportFilter class, TfrTextExportFilter define two more properties.<br />
*'''UsedFont''':integer. this property define the pixel dimensions on the output grid, objects on report are fitted into this grid by reclaculating each x and y position. The default value is 10, if user changes this value to 0 o less, LazReport will show automatically a dialog asking for the UsedFont value, if user enter a invalid value, a 10 value will be used. The 10 value is used because is the value that better fits the usual reports which are made with fonts 10-13 points.<br />
*'''UseBOM''':boolean. This property enable the inclusion of UTF-8 Byte Order Mark character at the start of text output (see [http://en.wikipedia.org/wiki/Byte_order_mark BOM]) needed by some editors/viewers, by default no BOM is used in exported output.<br />
===TfrCSVExportFilter===<br />
inheritance: TfrExportFilter <- TfrTextExportFilter <- TfrCSVExportFilter<br>located in: lr_e_csv.pas file included in LazReport package.<br />
<br />
This special text export filter produces Comma Separated Value output (actually any character can be used as separator), it differs from its ancestor in that it doesn't try to create text layout representation of graphical report, instead, for each record output it tries to guess the fields order from the source report, it then produce a list of fields using a separator defined by the user. Beside the properties inherited from its ancestor classes it defines some properties to customize the generated output.<br />
*'''QuoteType''':TfrQuoteType. This property controls whether the generated field value should be wrapped using specified quote char or not. Possible values are ''qtNone'', ''qtQuoteChar'' and ''qtAutoQuote''. With ''qtNone'' the field value is never wrapped, ''qtQuoteChar'' will use the character specified by property '''QuoteChar''', any instance of '''QuoteChar''' already present in field value is duplicated. ''qtAutoQuote'' first try to find if any instance of '''separator''' or '''QuoteChar''' is already present in field value, if affirmative it behaves as if ''qtQuoteChar'' has been specified, on the contrary case, the field value is not wrapped just as if ''qtNone'' has been specified. '''QuoteType''' property is set to ''qtQuoteChar'' by default.<br />
*'''QuoteChar''':TUTF8Char. This holds the character to be used to wrap the field value in case of '''QuoteType''' of value ''qtQuoteChar'' has been specified or deduced if ''qtAutoQuote'' is set. Any instance of this character in the field value will be duplicated. by default '''QuoteChar''' is set to the " character.<br />
*'''Separator''':TUTF8Char. This is the character used to separate the fields in each record, by default is set to the ',' (COMMA) character but any UTF-8 valid character could be used. Some CSV files are actually TAB separated files, to get this, set Separator:=#9;<br />
The CSV exporter do not use the inherited UsedFont property value so any value set will be ignored. With default property values, TfrCSVExportFilter will produce Excel compatible files, the only caveat is that Excel will not recognize the file as UTF-8 encoded. To force Excel to recognize the encoding automatically, set the property '''UseBOM''' to true.<br />
<br />
===TfrHTMExportFilter===<br />
inheritance: TfrExportFilter <- TfrTextExportFilter <- TfrHTMExportFilter. <br> Located in: lr_e_htm.pas in LazReport package.<br />
<br />
This special text export filter produces valid "HTML 4.01 Transitional" output. Currently it defines only one additional property.<br />
*'''UseCSS''':boolean. This property controls whether or not the produced output include CSS information, this property is set to true by default.<br />
<br />
==Script==<br />
A simple scripting language (interpreter) for a Pascal-like language is included in LazReport.<br />
<br />
Some notes:<br />
* the interpreter seems to expect semicolons after each line<br />
* the interpreter cannot handle nested if statements<br />
<br />
Example: this:<br />
<syntaxhighlight><br />
if [[PAY]>0] then begin<br />
if[[LATE_FEE]=1] then Text:=[MSGL2];<br />
else Text:= [MSGL1];<br />
end;<br />
</syntaxhighlight><br />
won't compile, while this will:<br />
<syntaxhighlight><br />
if[[LATE_FEE]=1] then Text:=[MSGL2];<br />
else Text:= [MSGL1];<br />
</syntaxhighlight><br />
<br />
Source: forum thread http://forum.lazarus.freepascal.org/index.php/topic,22902.0.html<br />
<br />
==Examples==<br />
You can find some examples in your Lazarus installation under components\lazreport\samples.<br />
<br />
=== Running total ===<br />
To calculate the total for values of each page added to the total on the previous page, follow these steps:<br />
* Make sure you have a report with a master data band connected to a dataset<br />
* Place a text inside that band and double click to open its editor.<br />
* In the editor, check the script option on the top left.<br />
* In the script window, paste the following code<br />
<syntaxhighlight><br />
IF [Line#] = 1 then RunTotal := [Dbf1."MTH_NO"]<br />
else RunTotal := RunTotal +[Dbf1."MTH_NO"]; <br />
</syntaxhighlight><br />
of course you need to replace [dbf1."MTH_NO"] with your field, the one you want a running total.<br />
* Click OK to save the changes.<br />
* Reopen the editor by double clicking on the text object<br />
* Click the "Variable" button.<br />
* Select the fr variables category in the drop down combo.<br />
* Double click the RunTotal variable to be placed on Memo.<br />
* Click OK and then press Preview.<br />
<br />
Source: {{MantisLink|17198}}<br />
<br />
==Tutorial==<br />
Please see [[LazReport Tutorial]].<br />
<br />
==See also==<br />
* [http://www.pp4s.co.uk/main/tu-db-firebird-demo3.html Creating and printing a report]<br />
<br />
=Report Designer=<br />
*Menu: File->Save As ... <br />
**Templates Notice:<br />
***While saving the current report, the user can select an arbitrary directory in the Save As dialog, in the case of templates (.lrt extension), the selected directory is ignored. Templates are always stored in the '''Templates Directory'''. The '''Templates Directory''' value can be set by either changing the frTemplateDir global variable (lr_desgn.pas unit) or by setting the TemplateDir property in a TfrDesigner component. The TemplateDir property will overwrite the frTemplateDir global variable if both are used. The '''Templates Directory''' can be an absolute path or a relative to program path directory, if this directory do not exists, LazReport will try to create it on the first use. If the TemplateDir property or the frTempateDir variable are not set, LazReport will try to save the templates in the program directory.<br />
***Binary templates format (.frt) is not recommended, as binary formats are hard to keep compatible with newer (or older) LazReport versions. If possible use .lrt file extension (XML file format).<br />
<br />
=Quick Start=<br />
==Report Records from a Dataset==<br />
In this sample we will design a report to print records from a dataset derived component (TDbf, TSQLQuery, TZTable, TZQuery, Etc.). First it's assumed that LazReport is already installed and the dataset component, called "Dbf1" here, is already configured and active. <br />
#From LazReport tab, select TfrReport component and drop it in Form Designer, it will be named "frReport1".<br />
#Drop a TfrDbDataset component, it will be named "frDbDataset1"<br />
#Drop a TButton, it will be named Button1, change its name to "btnShowReport"<br />
#With frDbDataset1 selected in Object Inspector select "Dbf1" for the "Dataset" property<br />
#Now select frReport1 and using the same procedure link its "Dataset" property to "frDbDataset1":<p><center>[[Image:lrformsetup.png]]</center></p><br />
#Right Click frReport1 and select "Design Report" from the menu, LazReport report designer will appear.<br />
#From Designer window, select menu Tools->Tools->Insert DB Fields, Insert fields Dialog will appear.<br />
#In field list select the fields you want in the report<br />
#Check "Include Headers" and "Include Bands" options, the result should be something like this:<p><center>[[Image:lrinsertfieldsdialog.png]]</center></p><br />
#Press the "Ok" button, LazReport will arrange bands and fields like this:<p><center> [[Image:lrreportwithfields.png]]</center></p><br />
#Press the preview button [[Image:lrprevieweye.png]], LazReport will then arrange things and show:<p><center>[[Image:lrpreviewreport.png]]</center></p><br />
#Save the report with Menu File->Save, select the same directory as the current project and name it as listing1.lrf<br />
#Close the report designer.<br />
#Double click btnShowReport and type the following code:<br />
<syntaxhighlight><br />
frReport1.LoadFromFile('listing1.lrf');<br />
frReport1.ShowReport;<br />
</syntaxhighlight><br />
<br />
=Bug reports=<br />
Please report problems using the <br />
[http://www.freepascal.org/mantis/main_page.php lazarus/freepascal bugtracker], project: "Lazarus Packages", Category<br />
"LazReport".<br />
<br />
For patches, please submit a bug report and attach the patch to it.<br />
<br />
[[Category:Components]]<br />
[[Category:Lazarus]]<br />
[[Category:LazReport]]</div>Mario13https://wiki.freepascal.org/index.php?title=LazReport_Documentation/es&diff=116761LazReport Documentation/es2018-03-29T14:21:54Z<p>Mario13: /* Funciones Numéricas */</p>
<hr />
<div>{{LazReport Documentation}}[[category:Español|?]][[category:Castellano|?]]<br />
<br />
=PRESENTACIÓN=<br />
LazReport es un grupo de componentes que agregan a las aplicaciones la capacidad de generar reportes, usa un diseñador visual para crear reportes basados en bandas e incluye un mecanismo de reportes con previsualizador que ademas incluye un interprete para ejecutar guiones de usuario. El diseñador de reportes puede ser invocado en tiempo de ejecución<br />
<br />
=LINCENCIA=<br />
LazReport se origina en FreeReport 2.32 y gracias a la compañía Fast Reports Inc. esta disponible bajo la licencia LGPL modificada, la misma licencia que usa la libreria LCL de Lazarus. Para mayor información, vea los archivos lazreport/ license.txt, license-rus.txt y licence-lazreport.txt<br />
<br />
=AUTORES=<br />
FreeReport fué creado por la compañía Fast Reports Inc. <br />
La adaptación inicial del código a LazReport fue hecha por Olivier Guilbaud, para mayor infomación visite el sitio original de LazReport en SourceForge http://lazreport.sourceforge.net/.<br />
La integración en Lazarus y actual encargado del proyecto es Jesús Reyes Aguilar.<br />
LazReport no podría haber llegado a su estado actual sin la colaboración de muchos otros desarrolladores, vea el archivo lazreport/doc/contributors.txt<br />
<br />
=INSTALACIÓN=<br />
Para Instalar LazReport en Lazarus:<br />
<br />
# Abrir el paquete LazReport Package. Menú: Componentes->Abrir archivo de paquete (.lpk)...<br />
# Abrir archivo components/lazreport/source/lazreport.lpk<br />
# Instalar<br />
<br />
La siguiente vez que Lazarus sea iniciado, debería mostrar una separador LazReport en la paleta de componentes.<br />
<br />
=DOCUMENTACIÓN=<br />
El Manual del Desarrollador y La Guia del Usuario específicas para LazReport están aún por escribirse, mientras tanto, la mayoría de las funciones de LazReport están descritas en el Manual del Desarrollador de FreeReport (vea lazreport/doc/fr_eng.sxw en la instalción de Lazarus), Algunas cosas dependientes de la plataforma descritas allí, como objetos OLE, no están implementados en LazReport. También algunos ejemplos o imágenes hacen referencia a ejemplos que están disponibles solamente en Delphi.<br />
<br />
Hasta que la documentación especifica para LazReport sea elaborada, ésta página wiki será usada como repositorio de documentación, quizás en el futuro la documentación faltante pueda ser generada desde aquí. Se alienta a los usuarios a que agreguen temas que sientan haya necesidad de documentar, incluso si la descripción o contenido de dichos temas deba ser proporcionado por otros usuarios.<br />
<br />
== Operadores ==<br />
<br />
Los siguientes operadores están soportados:<br />
{| BORDER="1" CELLSPACING="0"<br />
!COLSPAN="1" STYLE="background:#ffdead;"|Tipo Operador<br />
!COLSPAN="1" STYLE="background:#ffdead;"|Operador<br />
|---- <br />
|Logicos||>, <, BUT, AND, NOT, =, < >, >=, <= <br />
|---- <br />
|Aritméticos||-, *, +, MOD, /<br />
|}<br />
<br />
==Funciones==<br />
Las siguientes funciones están disponibles:<br />
===Funciones de agregación===<br />
;SUM(<X>) : Devuelve la suma de valores representados por <X>, que generalmente es un campo de datos. <br />
;AVG(<X>) : Devuelve el promedio de los valore de <X>.<br />
;COUNT : Cuenta la cantidad de ocurrencias o registros.<br />
;MIN(<X>) : Devuelve le menor valor de todos los posibles valores de <X>.<br />
;MAX(<X>) : Devuelve le mayor valor de todos los posibles valores de <X>.<br />
<br />
===Funciones de formateo===<br />
;FORMATDATETIME(<X>, <Y>) : Devuelve una cadena con el valor <Y> (de tipo TDateTime) en el formato <X>. <X> usa la sintaxis default de los [http://www.freepascal.org/docs-html/rtl/sysutils/formatdatetime.html formatos de Lazarus].<br />
;FORMATFLOAT(<X>, <Y>) : Devuelve una cadena con el valor numérico <Y> en el formato <X>. <X> usa la sintaxis default de los [http://www.freepascal.org/docs-html/rtl/sysutils/formatfloat.html formatos de Lazarus].<br />
;STRTODATE(<X>) : Devuelve la representación en fecha (tipo TDateTime) de la cadena <X>. <X> debe estar formateada correctamente.<br />
;STRTOTIME(<X>) : Devuelve la representación en tiempo (tipo TDateTime) de la cadena <X>. <X> debe estar formateada correctamente.<br />
<br />
===Funciones de cadenas===<br />
;LOWERCASE(<X>) : Devuelve <X> pasada a minúsculas.<br />
;UPPERCASE(<X>) : Devuelve <X> pasada a mayúsculas.<br />
;NAMECASE(<X>) : Devuelve <X> con una mayúscula inicial en cada palabra.<br />
;COPY(<X>, <Y>, <Z>) : Es similar a la función "copy" de Pascal: devuelve la porción de la cadena <X> desde la posición <Y> contando <Z> letras. <br />
<br />
===Funciones numéricas===<br />
;FRAC(<X>) : Devuelve la parte fraccionaria del número real <X>.<br />
;INT(<X>) : Devuelve la parte entera del número real <X>.<br />
;ROUND(<X>) : Devuelve el número real <X> redondeado al entero inmediato superior.<br />
;STR(<X>) : Devuelve una cadena representando al número <X>.<br />
<br />
===Funciones lógicas===<br />
;IF(<X>, <Y>, <Z>) : Devuelve <Y> si la expresión <X> es verdadera. Si es falsa, devuelve <Z>.<br />
<br />
==Agregando tus propias funciones==<br />
Aunque probablemente no se necesite demasiado, LazReport te permite definir tus propias funciones. Ver [[LazReport Documentation#Documentation]] para las funciones ya existentes.<br />
Para agregar tus propias funciones:<br />
<br />
<br />
==Filtros de Exportación==<br />
Los filtros de exportación de LazReport se invocan usando el siguiente código.<br />
<source> if TheReport.PrepareReport then<br />
TheReport.ExportTo(TfrHTMExportFilter, 'exportedfile.html');</source><br />
Donde TheReport contiene una instancia del componente TfrReport. En este ejemplo se usa<br />
TfrHTMExportFilter para generar un archivo llamado 'exportedfile.html'. No es necesario preparar de nuevo el reporte si éste ha sido preparado con anterioridad. Para poder hacer uso de TfrHTMExportFilter el programador debe arrastrar y soltar un componente TfrHTMExportFilter desde el separador LazReport en la paleta de componentes, hacia el Diseñador de Formularios. Como una alternativa se puede añadir manualmente lr_e_htm a la clausula "uses" de la unidad.<br />
<br />
A partir de la versión 0.9.6 de LazReport el soporte de filtros de exportación ha sido mejorado, ahora los filtros de exportación pueden tomar parámetros que los usuarios pueden manipular ya sea cambiando los valores directamente o presentando al usuario final alguna interfaz de usuario. Para poder hacer cambios en los parametros, el programador debe crear un manipulador para el evento TfrReport.OnExportFilterSetup, disponible al seleccionar el componente TfrReport en el separador "Eventos" del Inspector de Objetos.<br />
<br />
El método manipulador del evento OnExportFilterSetup (de tipo TExportFilterSetup) toma un parámetro "sender" del tipo TfrExportFilter, para poder usar este tipo se debe añadir la unidad lr_class.pas a la clausula uses de la unidad. Todas la clases del tipo ExportFilter comparten este evento y el programador debe hacer un type-cast a la clase del filtro de exportación deseado, por ejemplo:<br />
<source> if sender is TfrHTMExportFilter then<br />
begin<br />
TfrHTMExportFilter(sender).UseCSS := false;<br />
end;</source><br />
A continuación una descripción de los filtros de exportación disponibles.<br />
<br />
===TfrExportFilter===<br />
&nbsp;&nbsp;&nbsp; Esta es la clase báse de todos los filtros de exportación, y defines dos propiedades que pueden ser modificadas por el desarrollador en el evento '''''OnExportFilterSetup''''':<br />
*'''BandTypes''': TfrBandTypes. Se trata de un conjunto de tipos de bandas, solo las bandas incluidas en este conjunto son efectivamente exportada, el resto de las bandas presentes en el informe se ignorarán. Usando esta propiedad un programador podría, por ejemplo, exportar sólo el contenido de la banda principal, dejando los títulos, encabezados y pies de página fuera de la salida exportada así:<br />
<source> sender.BandTypes := [btMasterData];</source><br />
de forma predeterminada, todas las bandas son procesadas pero ''TfrCSVExportFilter'' cambia esta propiedad para procesar únicamente la cabecera principal, las cabeceras de columna y las bandas principales de datos.<br />
*'''UseProgressbar''': boolean. Esta propiedad activa o desactiva la visualización de la barra de progreso del filtro de exportación. La propiedad tiene el valor predefinido como falso.<br />
<br />
===TfrTextExportFilter===<br />
&nbsp;&nbsp;&nbsp; Hereda de: TfrExportFilter <- TfrTextExportFilter<br>localizado en el archivo '''lr_e_txt.pas''' incluido en el paquete LazReport.<br />
<br />
&nbsp;&nbsp;&nbsp;Es la clase base de los filtros de texto. Este filtro de exportación trata de hacer una representación en texto de un informe gráfico mediante el ajuste de las coordenadas gráficas originales en una rejilla más gruesa donde cada unidad es un punto de la fuente ''UsedFont'', dependiendo del valor de ''UsedFont'', la salida exportada será más o menos parecida al diseño de objetos en el informe gráfico.<br />
<br />
&nbsp;&nbsp;&nbsp;Además de las propiedades heredadas de la clase TfrExportFilter, TfrTextExportFilter define dos propiedades más.<br />
*'''UsedFont''': integer. Esta propiedad define las dimensiones en puntos de la rejilla de salida, los objetos en el informe se colocan en esta red recalculando las posiciones x e y. El valor predeterminado es 10, si el usuario cambia este valor a 0 o menos, LazReport mostrará automáticamente un cuadro de diálogo preguntando por el valor UsedFont, si el usuario introduce un valor no válido, se utilizará el valor 10. Ee utiliza el valor 10 porque es el valor que mejor se adapta a los informes habituales que se hacen con las fuentes de 10-13 puntos.<br />
*'''UseBOM''': boolean. Esta propiedad permitirá la inclusión de caracteres UTF-8 con ''Byte Order Mark'' al comienzo de la salida de texto (ver [http://en.wikipedia.org/wiki/Byte_order_mark BOM]) que es requerido por algunos editores/visores, ya que BOM no se utiliza de forma predeterminada.<br />
<br />
===TfrCSVExportFilter===<br />
inheritance: TfrExportFilter <- TfrTextExportFilter <- TfrCSVExportFilter<br>located in: lr_e_csv.pas file included in LazReport package.<br />
<br />
This special text export filter produces Comma Separated Value output (actually any character can be used as separator), it differs from it's ancestor in that it doesn't try to create text layout representation of graphical report, instead, for each record output it tries to guess the fields order from the source report, it then produce a list of fields using a separator defined by the user. Beside the properties inherited from its ancestor classes it defines some properties to customize the generated output.<br />
*'''QuoteType''':TfrQuoteType. This property controls whether the generated field value should be wrapped using specified quote char or not. Possible values are ''qtNone'', ''qtQuoteChar'' and ''qtAutoQuote''. With ''qtNone'' the field value is never wrapped, ''qtQuoteChar'' will use the character specified by property '''QuoteChar''', any instance of '''QuoteChar''' already present in field value is duplicated. ''qtAutoQuote'' first try to find if any instance of '''separator''' or '''QuoteChar''' is already present in field value, if affirmative it behaves as if ''qtQuoteChar'' has been specified, on the contrary case, the field value is not wrapped just as if ''qtNone'' has been specified. '''QuoteType''' property is set to ''qtQuoteChar'' by default.<br />
*'''QuoteChar''':TUTF8Char. This holds the character to be used to wrap the field value in case of '''QuoteType''' of value ''qtQuoteChar'' has been specified or deduced if ''qtAutoQuote'' is set. Any instance of this character in the field value will be duplicated. by default '''QuoteChar''' is set to the " character.<br />
*'''Separator''':TUTF8Char. This is the character used to separate the fields in each record, by default is set to the ',' (COMMA) character but any UTF-8 valid character could be used. Some CSV files are actually TAB separated files, to get this, set Separator:=#9;<br />
The CSV exporter do not use the inherited UsedFont property value so any value set will be ignored. With default property values, TfrCSVExportFilter will produce Excel compatible files, the only caveat is that Excel will not recognize the file as UTF-8 encoded. To force Excel to recognize the encoding automatically, set the property '''UseBOM''' to true.<br />
===TfrHTMExportFilter===<br />
inheritance: TfrExportFilter <- TfrTextExportFilter <- TfrHTMExportFilter. <br> Located in: lr_e_htm.pas in LazReport package.<br />
<br />
This special text export filter produces valid "HTML 4.01 Transitional" output. Currently it defines only one additional property.<br />
*'''UseCSS''':boolean. This property controls whether or not the produced output include CSS information, this property is set to true by default.<br />
<br />
=INICIO RÁPIDO=<br />
==Reporte de Registros de un Dataset==<br />
En este ejemplo diseñaremos un reporte para imprimir registros desde un componente derivado de TDataset (TDbf, TSQLQuery, TZTable, TZQuery, Etcetera.). Primero se supone que LazReport ya esta instalado y que el componente dataset, llamado "Dbf1" aquí, ya esta configurado y activo. <br />
#Del separador LazReport en la paleta de componentes, seleccionamos el componente TfrReport y lo arrojamos en el Diseñador de Formularios, será nombrado automáticamente "frReport1".<br />
#Colocar también un componente TfrDbDataset, será nombrado "frDbDataset1"<br />
#Colocar un componente TButton, será nombrado "Button1", cambie su nombre a "btnShowReport"<br />
#Con el componente frDbDataset1 seleccionado, en el Inspector de Objectos seleccione "Dbf1" en la propiedad "Dataset"<br />
#Ahora seleccione frReport1 y usando el mismo procedimiento enlace su propiedad "Dataset" al componente "frDbDataset1":<p><center>[[Image:lrformsetup.png]]</center></p><br />
#Haga clic con el botón derecho sobre frReport1 y del menú seleccione "Diseñar Reporte". Se mostrará El Diseñador de Reportes de LazReport.<br />
#En la ventana del Diseñador de LazReport, seleccione el menu Herramientas->Herramientas->Insertar Campos DB. El diálogo "Insertar Campos" aparecerá.<br />
#En la lista de campos seleccione los campos que desee que aparezcan en el reporte<br />
#Seleccione las opciones "Incluir Encabezados" y "Incluir Bandas", el resultado debería ser similar a esto:<p><center>[[Image:lrinsertfieldsdialog.png]]</center></p><br />
#Presione el botón "Aceptar", LazReport colocara bandas y campos en el reporte de una formasimilar a la siguiente:<p><center>[[Image:lrreportwithfields.png]]</center></p><br />
#Presione el boton de Vista Previa [[Image:lrprevieweye.png]], LazReport mostrará entonces una vista previa del reporte:<p><center>[[Image:lrpreviewreport.png]]</center></p><br />
#Guarde el reporte usando el menú Archivos->Guardar, seleccione el mismo directorio del proyecto actual y guardelo como listing1.lrf<br />
#Cierre el Diseñador de Reportes.<br />
#Haga doble clic sobre el botón btnShowReport y teclee el siguiente código:<br />
<source> frReport1.LoadFromFile('listing1.lrf');<br />
frReport1.ShowReport;</source><br />
<br />
=Informar sobre errores=<br />
&nbsp;&nbsp;&nbsp;Por favor informa sobre los problemas utilizando el <br />
[http://www.freepascal.org/mantis/main_page.php seguimiento de errores (''bugtracker'') de lazarus/free pascal], en el proyecto: "Lazarus Packages", Categoría<br />
"LazReport"; para remitir parches por favor, crea un informe de error y adjunta el parche al mismo.<br />
<br />
----</div>Mario13https://wiki.freepascal.org/index.php?title=LazReport_Documentation/es&diff=116760LazReport Documentation/es2018-03-29T14:21:32Z<p>Mario13: /* Logical/boolean functions */</p>
<hr />
<div>{{LazReport Documentation}}[[category:Español|?]][[category:Castellano|?]]<br />
<br />
=PRESENTACIÓN=<br />
LazReport es un grupo de componentes que agregan a las aplicaciones la capacidad de generar reportes, usa un diseñador visual para crear reportes basados en bandas e incluye un mecanismo de reportes con previsualizador que ademas incluye un interprete para ejecutar guiones de usuario. El diseñador de reportes puede ser invocado en tiempo de ejecución<br />
<br />
=LINCENCIA=<br />
LazReport se origina en FreeReport 2.32 y gracias a la compañía Fast Reports Inc. esta disponible bajo la licencia LGPL modificada, la misma licencia que usa la libreria LCL de Lazarus. Para mayor información, vea los archivos lazreport/ license.txt, license-rus.txt y licence-lazreport.txt<br />
<br />
=AUTORES=<br />
FreeReport fué creado por la compañía Fast Reports Inc. <br />
La adaptación inicial del código a LazReport fue hecha por Olivier Guilbaud, para mayor infomación visite el sitio original de LazReport en SourceForge http://lazreport.sourceforge.net/.<br />
La integración en Lazarus y actual encargado del proyecto es Jesús Reyes Aguilar.<br />
LazReport no podría haber llegado a su estado actual sin la colaboración de muchos otros desarrolladores, vea el archivo lazreport/doc/contributors.txt<br />
<br />
=INSTALACIÓN=<br />
Para Instalar LazReport en Lazarus:<br />
<br />
# Abrir el paquete LazReport Package. Menú: Componentes->Abrir archivo de paquete (.lpk)...<br />
# Abrir archivo components/lazreport/source/lazreport.lpk<br />
# Instalar<br />
<br />
La siguiente vez que Lazarus sea iniciado, debería mostrar una separador LazReport en la paleta de componentes.<br />
<br />
=DOCUMENTACIÓN=<br />
El Manual del Desarrollador y La Guia del Usuario específicas para LazReport están aún por escribirse, mientras tanto, la mayoría de las funciones de LazReport están descritas en el Manual del Desarrollador de FreeReport (vea lazreport/doc/fr_eng.sxw en la instalción de Lazarus), Algunas cosas dependientes de la plataforma descritas allí, como objetos OLE, no están implementados en LazReport. También algunos ejemplos o imágenes hacen referencia a ejemplos que están disponibles solamente en Delphi.<br />
<br />
Hasta que la documentación especifica para LazReport sea elaborada, ésta página wiki será usada como repositorio de documentación, quizás en el futuro la documentación faltante pueda ser generada desde aquí. Se alienta a los usuarios a que agreguen temas que sientan haya necesidad de documentar, incluso si la descripción o contenido de dichos temas deba ser proporcionado por otros usuarios.<br />
<br />
== Operadores ==<br />
<br />
Los siguientes operadores están soportados:<br />
{| BORDER="1" CELLSPACING="0"<br />
!COLSPAN="1" STYLE="background:#ffdead;"|Tipo Operador<br />
!COLSPAN="1" STYLE="background:#ffdead;"|Operador<br />
|---- <br />
|Logicos||>, <, BUT, AND, NOT, =, < >, >=, <= <br />
|---- <br />
|Aritméticos||-, *, +, MOD, /<br />
|}<br />
<br />
==Funciones==<br />
Las siguientes funciones están disponibles:<br />
===Funciones de agregación===<br />
;SUM(<X>) : Devuelve la suma de valores representados por <X>, que generalmente es un campo de datos. <br />
;AVG(<X>) : Devuelve el promedio de los valore de <X>.<br />
;COUNT : Cuenta la cantidad de ocurrencias o registros.<br />
;MIN(<X>) : Devuelve le menor valor de todos los posibles valores de <X>.<br />
;MAX(<X>) : Devuelve le mayor valor de todos los posibles valores de <X>.<br />
<br />
===Funciones de formateo===<br />
;FORMATDATETIME(<X>, <Y>) : Devuelve una cadena con el valor <Y> (de tipo TDateTime) en el formato <X>. <X> usa la sintaxis default de los [http://www.freepascal.org/docs-html/rtl/sysutils/formatdatetime.html formatos de Lazarus].<br />
;FORMATFLOAT(<X>, <Y>) : Devuelve una cadena con el valor numérico <Y> en el formato <X>. <X> usa la sintaxis default de los [http://www.freepascal.org/docs-html/rtl/sysutils/formatfloat.html formatos de Lazarus].<br />
;STRTODATE(<X>) : Devuelve la representación en fecha (tipo TDateTime) de la cadena <X>. <X> debe estar formateada correctamente.<br />
;STRTOTIME(<X>) : Devuelve la representación en tiempo (tipo TDateTime) de la cadena <X>. <X> debe estar formateada correctamente.<br />
<br />
===Funciones de cadenas===<br />
;LOWERCASE(<X>) : Devuelve <X> pasada a minúsculas.<br />
;UPPERCASE(<X>) : Devuelve <X> pasada a mayúsculas.<br />
;NAMECASE(<X>) : Devuelve <X> con una mayúscula inicial en cada palabra.<br />
;COPY(<X>, <Y>, <Z>) : Es similar a la función "copy" de Pascal: devuelve la porción de la cadena <X> desde la posición <Y> contando <Z> letras. <br />
<br />
===Funciones Numéricas===<br />
;FRAC(<X>) : Devuelve la parte fraccionaria del número real <X>.<br />
;INT(<X>) : Devuelve la parte entera del número real <X>.<br />
;ROUND(<X>) : Devuelve el número real <X> redondeado al entero inmediato superior.<br />
;STR(<X>) : Devuelve una cadena representando al número <X>.<br />
<br />
===Funciones lógicas===<br />
;IF(<X>, <Y>, <Z>) : Devuelve <Y> si la expresión <X> es verdadera. Si es falsa, devuelve <Z>.<br />
<br />
==Agregando tus propias funciones==<br />
Aunque probablemente no se necesite demasiado, LazReport te permite definir tus propias funciones. Ver [[LazReport Documentation#Documentation]] para las funciones ya existentes.<br />
Para agregar tus propias funciones:<br />
<br />
<br />
==Filtros de Exportación==<br />
Los filtros de exportación de LazReport se invocan usando el siguiente código.<br />
<source> if TheReport.PrepareReport then<br />
TheReport.ExportTo(TfrHTMExportFilter, 'exportedfile.html');</source><br />
Donde TheReport contiene una instancia del componente TfrReport. En este ejemplo se usa<br />
TfrHTMExportFilter para generar un archivo llamado 'exportedfile.html'. No es necesario preparar de nuevo el reporte si éste ha sido preparado con anterioridad. Para poder hacer uso de TfrHTMExportFilter el programador debe arrastrar y soltar un componente TfrHTMExportFilter desde el separador LazReport en la paleta de componentes, hacia el Diseñador de Formularios. Como una alternativa se puede añadir manualmente lr_e_htm a la clausula "uses" de la unidad.<br />
<br />
A partir de la versión 0.9.6 de LazReport el soporte de filtros de exportación ha sido mejorado, ahora los filtros de exportación pueden tomar parámetros que los usuarios pueden manipular ya sea cambiando los valores directamente o presentando al usuario final alguna interfaz de usuario. Para poder hacer cambios en los parametros, el programador debe crear un manipulador para el evento TfrReport.OnExportFilterSetup, disponible al seleccionar el componente TfrReport en el separador "Eventos" del Inspector de Objetos.<br />
<br />
El método manipulador del evento OnExportFilterSetup (de tipo TExportFilterSetup) toma un parámetro "sender" del tipo TfrExportFilter, para poder usar este tipo se debe añadir la unidad lr_class.pas a la clausula uses de la unidad. Todas la clases del tipo ExportFilter comparten este evento y el programador debe hacer un type-cast a la clase del filtro de exportación deseado, por ejemplo:<br />
<source> if sender is TfrHTMExportFilter then<br />
begin<br />
TfrHTMExportFilter(sender).UseCSS := false;<br />
end;</source><br />
A continuación una descripción de los filtros de exportación disponibles.<br />
<br />
===TfrExportFilter===<br />
&nbsp;&nbsp;&nbsp; Esta es la clase báse de todos los filtros de exportación, y defines dos propiedades que pueden ser modificadas por el desarrollador en el evento '''''OnExportFilterSetup''''':<br />
*'''BandTypes''': TfrBandTypes. Se trata de un conjunto de tipos de bandas, solo las bandas incluidas en este conjunto son efectivamente exportada, el resto de las bandas presentes en el informe se ignorarán. Usando esta propiedad un programador podría, por ejemplo, exportar sólo el contenido de la banda principal, dejando los títulos, encabezados y pies de página fuera de la salida exportada así:<br />
<source> sender.BandTypes := [btMasterData];</source><br />
de forma predeterminada, todas las bandas son procesadas pero ''TfrCSVExportFilter'' cambia esta propiedad para procesar únicamente la cabecera principal, las cabeceras de columna y las bandas principales de datos.<br />
*'''UseProgressbar''': boolean. Esta propiedad activa o desactiva la visualización de la barra de progreso del filtro de exportación. La propiedad tiene el valor predefinido como falso.<br />
<br />
===TfrTextExportFilter===<br />
&nbsp;&nbsp;&nbsp; Hereda de: TfrExportFilter <- TfrTextExportFilter<br>localizado en el archivo '''lr_e_txt.pas''' incluido en el paquete LazReport.<br />
<br />
&nbsp;&nbsp;&nbsp;Es la clase base de los filtros de texto. Este filtro de exportación trata de hacer una representación en texto de un informe gráfico mediante el ajuste de las coordenadas gráficas originales en una rejilla más gruesa donde cada unidad es un punto de la fuente ''UsedFont'', dependiendo del valor de ''UsedFont'', la salida exportada será más o menos parecida al diseño de objetos en el informe gráfico.<br />
<br />
&nbsp;&nbsp;&nbsp;Además de las propiedades heredadas de la clase TfrExportFilter, TfrTextExportFilter define dos propiedades más.<br />
*'''UsedFont''': integer. Esta propiedad define las dimensiones en puntos de la rejilla de salida, los objetos en el informe se colocan en esta red recalculando las posiciones x e y. El valor predeterminado es 10, si el usuario cambia este valor a 0 o menos, LazReport mostrará automáticamente un cuadro de diálogo preguntando por el valor UsedFont, si el usuario introduce un valor no válido, se utilizará el valor 10. Ee utiliza el valor 10 porque es el valor que mejor se adapta a los informes habituales que se hacen con las fuentes de 10-13 puntos.<br />
*'''UseBOM''': boolean. Esta propiedad permitirá la inclusión de caracteres UTF-8 con ''Byte Order Mark'' al comienzo de la salida de texto (ver [http://en.wikipedia.org/wiki/Byte_order_mark BOM]) que es requerido por algunos editores/visores, ya que BOM no se utiliza de forma predeterminada.<br />
<br />
===TfrCSVExportFilter===<br />
inheritance: TfrExportFilter <- TfrTextExportFilter <- TfrCSVExportFilter<br>located in: lr_e_csv.pas file included in LazReport package.<br />
<br />
This special text export filter produces Comma Separated Value output (actually any character can be used as separator), it differs from it's ancestor in that it doesn't try to create text layout representation of graphical report, instead, for each record output it tries to guess the fields order from the source report, it then produce a list of fields using a separator defined by the user. Beside the properties inherited from its ancestor classes it defines some properties to customize the generated output.<br />
*'''QuoteType''':TfrQuoteType. This property controls whether the generated field value should be wrapped using specified quote char or not. Possible values are ''qtNone'', ''qtQuoteChar'' and ''qtAutoQuote''. With ''qtNone'' the field value is never wrapped, ''qtQuoteChar'' will use the character specified by property '''QuoteChar''', any instance of '''QuoteChar''' already present in field value is duplicated. ''qtAutoQuote'' first try to find if any instance of '''separator''' or '''QuoteChar''' is already present in field value, if affirmative it behaves as if ''qtQuoteChar'' has been specified, on the contrary case, the field value is not wrapped just as if ''qtNone'' has been specified. '''QuoteType''' property is set to ''qtQuoteChar'' by default.<br />
*'''QuoteChar''':TUTF8Char. This holds the character to be used to wrap the field value in case of '''QuoteType''' of value ''qtQuoteChar'' has been specified or deduced if ''qtAutoQuote'' is set. Any instance of this character in the field value will be duplicated. by default '''QuoteChar''' is set to the " character.<br />
*'''Separator''':TUTF8Char. This is the character used to separate the fields in each record, by default is set to the ',' (COMMA) character but any UTF-8 valid character could be used. Some CSV files are actually TAB separated files, to get this, set Separator:=#9;<br />
The CSV exporter do not use the inherited UsedFont property value so any value set will be ignored. With default property values, TfrCSVExportFilter will produce Excel compatible files, the only caveat is that Excel will not recognize the file as UTF-8 encoded. To force Excel to recognize the encoding automatically, set the property '''UseBOM''' to true.<br />
===TfrHTMExportFilter===<br />
inheritance: TfrExportFilter <- TfrTextExportFilter <- TfrHTMExportFilter. <br> Located in: lr_e_htm.pas in LazReport package.<br />
<br />
This special text export filter produces valid "HTML 4.01 Transitional" output. Currently it defines only one additional property.<br />
*'''UseCSS''':boolean. This property controls whether or not the produced output include CSS information, this property is set to true by default.<br />
<br />
=INICIO RÁPIDO=<br />
==Reporte de Registros de un Dataset==<br />
En este ejemplo diseñaremos un reporte para imprimir registros desde un componente derivado de TDataset (TDbf, TSQLQuery, TZTable, TZQuery, Etcetera.). Primero se supone que LazReport ya esta instalado y que el componente dataset, llamado "Dbf1" aquí, ya esta configurado y activo. <br />
#Del separador LazReport en la paleta de componentes, seleccionamos el componente TfrReport y lo arrojamos en el Diseñador de Formularios, será nombrado automáticamente "frReport1".<br />
#Colocar también un componente TfrDbDataset, será nombrado "frDbDataset1"<br />
#Colocar un componente TButton, será nombrado "Button1", cambie su nombre a "btnShowReport"<br />
#Con el componente frDbDataset1 seleccionado, en el Inspector de Objectos seleccione "Dbf1" en la propiedad "Dataset"<br />
#Ahora seleccione frReport1 y usando el mismo procedimiento enlace su propiedad "Dataset" al componente "frDbDataset1":<p><center>[[Image:lrformsetup.png]]</center></p><br />
#Haga clic con el botón derecho sobre frReport1 y del menú seleccione "Diseñar Reporte". Se mostrará El Diseñador de Reportes de LazReport.<br />
#En la ventana del Diseñador de LazReport, seleccione el menu Herramientas->Herramientas->Insertar Campos DB. El diálogo "Insertar Campos" aparecerá.<br />
#En la lista de campos seleccione los campos que desee que aparezcan en el reporte<br />
#Seleccione las opciones "Incluir Encabezados" y "Incluir Bandas", el resultado debería ser similar a esto:<p><center>[[Image:lrinsertfieldsdialog.png]]</center></p><br />
#Presione el botón "Aceptar", LazReport colocara bandas y campos en el reporte de una formasimilar a la siguiente:<p><center>[[Image:lrreportwithfields.png]]</center></p><br />
#Presione el boton de Vista Previa [[Image:lrprevieweye.png]], LazReport mostrará entonces una vista previa del reporte:<p><center>[[Image:lrpreviewreport.png]]</center></p><br />
#Guarde el reporte usando el menú Archivos->Guardar, seleccione el mismo directorio del proyecto actual y guardelo como listing1.lrf<br />
#Cierre el Diseñador de Reportes.<br />
#Haga doble clic sobre el botón btnShowReport y teclee el siguiente código:<br />
<source> frReport1.LoadFromFile('listing1.lrf');<br />
frReport1.ShowReport;</source><br />
<br />
=Informar sobre errores=<br />
&nbsp;&nbsp;&nbsp;Por favor informa sobre los problemas utilizando el <br />
[http://www.freepascal.org/mantis/main_page.php seguimiento de errores (''bugtracker'') de lazarus/free pascal], en el proyecto: "Lazarus Packages", Categoría<br />
"LazReport"; para remitir parches por favor, crea un informe de error y adjunta el parche al mismo.<br />
<br />
----</div>Mario13https://wiki.freepascal.org/index.php?title=LazReport_Documentation/es&diff=116759LazReport Documentation/es2018-03-29T14:20:22Z<p>Mario13: /* Funciones */</p>
<hr />
<div>{{LazReport Documentation}}[[category:Español|?]][[category:Castellano|?]]<br />
<br />
=PRESENTACIÓN=<br />
LazReport es un grupo de componentes que agregan a las aplicaciones la capacidad de generar reportes, usa un diseñador visual para crear reportes basados en bandas e incluye un mecanismo de reportes con previsualizador que ademas incluye un interprete para ejecutar guiones de usuario. El diseñador de reportes puede ser invocado en tiempo de ejecución<br />
<br />
=LINCENCIA=<br />
LazReport se origina en FreeReport 2.32 y gracias a la compañía Fast Reports Inc. esta disponible bajo la licencia LGPL modificada, la misma licencia que usa la libreria LCL de Lazarus. Para mayor información, vea los archivos lazreport/ license.txt, license-rus.txt y licence-lazreport.txt<br />
<br />
=AUTORES=<br />
FreeReport fué creado por la compañía Fast Reports Inc. <br />
La adaptación inicial del código a LazReport fue hecha por Olivier Guilbaud, para mayor infomación visite el sitio original de LazReport en SourceForge http://lazreport.sourceforge.net/.<br />
La integración en Lazarus y actual encargado del proyecto es Jesús Reyes Aguilar.<br />
LazReport no podría haber llegado a su estado actual sin la colaboración de muchos otros desarrolladores, vea el archivo lazreport/doc/contributors.txt<br />
<br />
=INSTALACIÓN=<br />
Para Instalar LazReport en Lazarus:<br />
<br />
# Abrir el paquete LazReport Package. Menú: Componentes->Abrir archivo de paquete (.lpk)...<br />
# Abrir archivo components/lazreport/source/lazreport.lpk<br />
# Instalar<br />
<br />
La siguiente vez que Lazarus sea iniciado, debería mostrar una separador LazReport en la paleta de componentes.<br />
<br />
=DOCUMENTACIÓN=<br />
El Manual del Desarrollador y La Guia del Usuario específicas para LazReport están aún por escribirse, mientras tanto, la mayoría de las funciones de LazReport están descritas en el Manual del Desarrollador de FreeReport (vea lazreport/doc/fr_eng.sxw en la instalción de Lazarus), Algunas cosas dependientes de la plataforma descritas allí, como objetos OLE, no están implementados en LazReport. También algunos ejemplos o imágenes hacen referencia a ejemplos que están disponibles solamente en Delphi.<br />
<br />
Hasta que la documentación especifica para LazReport sea elaborada, ésta página wiki será usada como repositorio de documentación, quizás en el futuro la documentación faltante pueda ser generada desde aquí. Se alienta a los usuarios a que agreguen temas que sientan haya necesidad de documentar, incluso si la descripción o contenido de dichos temas deba ser proporcionado por otros usuarios.<br />
<br />
== Operadores ==<br />
<br />
Los siguientes operadores están soportados:<br />
{| BORDER="1" CELLSPACING="0"<br />
!COLSPAN="1" STYLE="background:#ffdead;"|Tipo Operador<br />
!COLSPAN="1" STYLE="background:#ffdead;"|Operador<br />
|---- <br />
|Logicos||>, <, BUT, AND, NOT, =, < >, >=, <= <br />
|---- <br />
|Aritméticos||-, *, +, MOD, /<br />
|}<br />
<br />
==Funciones==<br />
Las siguientes funciones están disponibles:<br />
===Funciones de agregación===<br />
;SUM(<X>) : Devuelve la suma de valores representados por <X>, que generalmente es un campo de datos. <br />
;AVG(<X>) : Devuelve el promedio de los valore de <X>.<br />
;COUNT : Cuenta la cantidad de ocurrencias o registros.<br />
;MIN(<X>) : Devuelve le menor valor de todos los posibles valores de <X>.<br />
;MAX(<X>) : Devuelve le mayor valor de todos los posibles valores de <X>.<br />
<br />
===Funciones de formateo===<br />
;FORMATDATETIME(<X>, <Y>) : Devuelve una cadena con el valor <Y> (de tipo TDateTime) en el formato <X>. <X> usa la sintaxis default de los [http://www.freepascal.org/docs-html/rtl/sysutils/formatdatetime.html formatos de Lazarus].<br />
;FORMATFLOAT(<X>, <Y>) : Devuelve una cadena con el valor numérico <Y> en el formato <X>. <X> usa la sintaxis default de los [http://www.freepascal.org/docs-html/rtl/sysutils/formatfloat.html formatos de Lazarus].<br />
;STRTODATE(<X>) : Devuelve la representación en fecha (tipo TDateTime) de la cadena <X>. <X> debe estar formateada correctamente.<br />
;STRTOTIME(<X>) : Devuelve la representación en tiempo (tipo TDateTime) de la cadena <X>. <X> debe estar formateada correctamente.<br />
<br />
===Funciones de cadenas===<br />
;LOWERCASE(<X>) : Devuelve <X> pasada a minúsculas.<br />
;UPPERCASE(<X>) : Devuelve <X> pasada a mayúsculas.<br />
;NAMECASE(<X>) : Devuelve <X> con una mayúscula inicial en cada palabra.<br />
;COPY(<X>, <Y>, <Z>) : Es similar a la función "copy" de Pascal: devuelve la porción de la cadena <X> desde la posición <Y> contando <Z> letras. <br />
<br />
===Funciones Numéricas===<br />
;FRAC(<X>) : Devuelve la parte fraccionaria del número real <X>.<br />
;INT(<X>) : Devuelve la parte entera del número real <X>.<br />
;ROUND(<X>) : Devuelve el número real <X> redondeado al entero inmediato superior.<br />
;STR(<X>) : Devuelve una cadena representando al número <X>.<br />
<br />
===Logical/boolean functions===<br />
;IF(<X>, <Y>, <Z>) : Devuelve <Y> si la expresión <X> es verdadera. Si es falsa, devuelve <Z>.<br />
<br />
==Agregando tus propias funciones==<br />
Aunque probablemente no se necesite demasiado, LazReport te permite definir tus propias funciones. Ver [[LazReport Documentation#Documentation]] para las funciones ya existentes.<br />
Para agregar tus propias funciones:<br />
<br />
<br />
==Filtros de Exportación==<br />
Los filtros de exportación de LazReport se invocan usando el siguiente código.<br />
<source> if TheReport.PrepareReport then<br />
TheReport.ExportTo(TfrHTMExportFilter, 'exportedfile.html');</source><br />
Donde TheReport contiene una instancia del componente TfrReport. En este ejemplo se usa<br />
TfrHTMExportFilter para generar un archivo llamado 'exportedfile.html'. No es necesario preparar de nuevo el reporte si éste ha sido preparado con anterioridad. Para poder hacer uso de TfrHTMExportFilter el programador debe arrastrar y soltar un componente TfrHTMExportFilter desde el separador LazReport en la paleta de componentes, hacia el Diseñador de Formularios. Como una alternativa se puede añadir manualmente lr_e_htm a la clausula "uses" de la unidad.<br />
<br />
A partir de la versión 0.9.6 de LazReport el soporte de filtros de exportación ha sido mejorado, ahora los filtros de exportación pueden tomar parámetros que los usuarios pueden manipular ya sea cambiando los valores directamente o presentando al usuario final alguna interfaz de usuario. Para poder hacer cambios en los parametros, el programador debe crear un manipulador para el evento TfrReport.OnExportFilterSetup, disponible al seleccionar el componente TfrReport en el separador "Eventos" del Inspector de Objetos.<br />
<br />
El método manipulador del evento OnExportFilterSetup (de tipo TExportFilterSetup) toma un parámetro "sender" del tipo TfrExportFilter, para poder usar este tipo se debe añadir la unidad lr_class.pas a la clausula uses de la unidad. Todas la clases del tipo ExportFilter comparten este evento y el programador debe hacer un type-cast a la clase del filtro de exportación deseado, por ejemplo:<br />
<source> if sender is TfrHTMExportFilter then<br />
begin<br />
TfrHTMExportFilter(sender).UseCSS := false;<br />
end;</source><br />
A continuación una descripción de los filtros de exportación disponibles.<br />
<br />
===TfrExportFilter===<br />
&nbsp;&nbsp;&nbsp; Esta es la clase báse de todos los filtros de exportación, y defines dos propiedades que pueden ser modificadas por el desarrollador en el evento '''''OnExportFilterSetup''''':<br />
*'''BandTypes''': TfrBandTypes. Se trata de un conjunto de tipos de bandas, solo las bandas incluidas en este conjunto son efectivamente exportada, el resto de las bandas presentes en el informe se ignorarán. Usando esta propiedad un programador podría, por ejemplo, exportar sólo el contenido de la banda principal, dejando los títulos, encabezados y pies de página fuera de la salida exportada así:<br />
<source> sender.BandTypes := [btMasterData];</source><br />
de forma predeterminada, todas las bandas son procesadas pero ''TfrCSVExportFilter'' cambia esta propiedad para procesar únicamente la cabecera principal, las cabeceras de columna y las bandas principales de datos.<br />
*'''UseProgressbar''': boolean. Esta propiedad activa o desactiva la visualización de la barra de progreso del filtro de exportación. La propiedad tiene el valor predefinido como falso.<br />
<br />
===TfrTextExportFilter===<br />
&nbsp;&nbsp;&nbsp; Hereda de: TfrExportFilter <- TfrTextExportFilter<br>localizado en el archivo '''lr_e_txt.pas''' incluido en el paquete LazReport.<br />
<br />
&nbsp;&nbsp;&nbsp;Es la clase base de los filtros de texto. Este filtro de exportación trata de hacer una representación en texto de un informe gráfico mediante el ajuste de las coordenadas gráficas originales en una rejilla más gruesa donde cada unidad es un punto de la fuente ''UsedFont'', dependiendo del valor de ''UsedFont'', la salida exportada será más o menos parecida al diseño de objetos en el informe gráfico.<br />
<br />
&nbsp;&nbsp;&nbsp;Además de las propiedades heredadas de la clase TfrExportFilter, TfrTextExportFilter define dos propiedades más.<br />
*'''UsedFont''': integer. Esta propiedad define las dimensiones en puntos de la rejilla de salida, los objetos en el informe se colocan en esta red recalculando las posiciones x e y. El valor predeterminado es 10, si el usuario cambia este valor a 0 o menos, LazReport mostrará automáticamente un cuadro de diálogo preguntando por el valor UsedFont, si el usuario introduce un valor no válido, se utilizará el valor 10. Ee utiliza el valor 10 porque es el valor que mejor se adapta a los informes habituales que se hacen con las fuentes de 10-13 puntos.<br />
*'''UseBOM''': boolean. Esta propiedad permitirá la inclusión de caracteres UTF-8 con ''Byte Order Mark'' al comienzo de la salida de texto (ver [http://en.wikipedia.org/wiki/Byte_order_mark BOM]) que es requerido por algunos editores/visores, ya que BOM no se utiliza de forma predeterminada.<br />
<br />
===TfrCSVExportFilter===<br />
inheritance: TfrExportFilter <- TfrTextExportFilter <- TfrCSVExportFilter<br>located in: lr_e_csv.pas file included in LazReport package.<br />
<br />
This special text export filter produces Comma Separated Value output (actually any character can be used as separator), it differs from it's ancestor in that it doesn't try to create text layout representation of graphical report, instead, for each record output it tries to guess the fields order from the source report, it then produce a list of fields using a separator defined by the user. Beside the properties inherited from its ancestor classes it defines some properties to customize the generated output.<br />
*'''QuoteType''':TfrQuoteType. This property controls whether the generated field value should be wrapped using specified quote char or not. Possible values are ''qtNone'', ''qtQuoteChar'' and ''qtAutoQuote''. With ''qtNone'' the field value is never wrapped, ''qtQuoteChar'' will use the character specified by property '''QuoteChar''', any instance of '''QuoteChar''' already present in field value is duplicated. ''qtAutoQuote'' first try to find if any instance of '''separator''' or '''QuoteChar''' is already present in field value, if affirmative it behaves as if ''qtQuoteChar'' has been specified, on the contrary case, the field value is not wrapped just as if ''qtNone'' has been specified. '''QuoteType''' property is set to ''qtQuoteChar'' by default.<br />
*'''QuoteChar''':TUTF8Char. This holds the character to be used to wrap the field value in case of '''QuoteType''' of value ''qtQuoteChar'' has been specified or deduced if ''qtAutoQuote'' is set. Any instance of this character in the field value will be duplicated. by default '''QuoteChar''' is set to the " character.<br />
*'''Separator''':TUTF8Char. This is the character used to separate the fields in each record, by default is set to the ',' (COMMA) character but any UTF-8 valid character could be used. Some CSV files are actually TAB separated files, to get this, set Separator:=#9;<br />
The CSV exporter do not use the inherited UsedFont property value so any value set will be ignored. With default property values, TfrCSVExportFilter will produce Excel compatible files, the only caveat is that Excel will not recognize the file as UTF-8 encoded. To force Excel to recognize the encoding automatically, set the property '''UseBOM''' to true.<br />
===TfrHTMExportFilter===<br />
inheritance: TfrExportFilter <- TfrTextExportFilter <- TfrHTMExportFilter. <br> Located in: lr_e_htm.pas in LazReport package.<br />
<br />
This special text export filter produces valid "HTML 4.01 Transitional" output. Currently it defines only one additional property.<br />
*'''UseCSS''':boolean. This property controls whether or not the produced output include CSS information, this property is set to true by default.<br />
<br />
=INICIO RÁPIDO=<br />
==Reporte de Registros de un Dataset==<br />
En este ejemplo diseñaremos un reporte para imprimir registros desde un componente derivado de TDataset (TDbf, TSQLQuery, TZTable, TZQuery, Etcetera.). Primero se supone que LazReport ya esta instalado y que el componente dataset, llamado "Dbf1" aquí, ya esta configurado y activo. <br />
#Del separador LazReport en la paleta de componentes, seleccionamos el componente TfrReport y lo arrojamos en el Diseñador de Formularios, será nombrado automáticamente "frReport1".<br />
#Colocar también un componente TfrDbDataset, será nombrado "frDbDataset1"<br />
#Colocar un componente TButton, será nombrado "Button1", cambie su nombre a "btnShowReport"<br />
#Con el componente frDbDataset1 seleccionado, en el Inspector de Objectos seleccione "Dbf1" en la propiedad "Dataset"<br />
#Ahora seleccione frReport1 y usando el mismo procedimiento enlace su propiedad "Dataset" al componente "frDbDataset1":<p><center>[[Image:lrformsetup.png]]</center></p><br />
#Haga clic con el botón derecho sobre frReport1 y del menú seleccione "Diseñar Reporte". Se mostrará El Diseñador de Reportes de LazReport.<br />
#En la ventana del Diseñador de LazReport, seleccione el menu Herramientas->Herramientas->Insertar Campos DB. El diálogo "Insertar Campos" aparecerá.<br />
#En la lista de campos seleccione los campos que desee que aparezcan en el reporte<br />
#Seleccione las opciones "Incluir Encabezados" y "Incluir Bandas", el resultado debería ser similar a esto:<p><center>[[Image:lrinsertfieldsdialog.png]]</center></p><br />
#Presione el botón "Aceptar", LazReport colocara bandas y campos en el reporte de una formasimilar a la siguiente:<p><center>[[Image:lrreportwithfields.png]]</center></p><br />
#Presione el boton de Vista Previa [[Image:lrprevieweye.png]], LazReport mostrará entonces una vista previa del reporte:<p><center>[[Image:lrpreviewreport.png]]</center></p><br />
#Guarde el reporte usando el menú Archivos->Guardar, seleccione el mismo directorio del proyecto actual y guardelo como listing1.lrf<br />
#Cierre el Diseñador de Reportes.<br />
#Haga doble clic sobre el botón btnShowReport y teclee el siguiente código:<br />
<source> frReport1.LoadFromFile('listing1.lrf');<br />
frReport1.ShowReport;</source><br />
<br />
=Informar sobre errores=<br />
&nbsp;&nbsp;&nbsp;Por favor informa sobre los problemas utilizando el <br />
[http://www.freepascal.org/mantis/main_page.php seguimiento de errores (''bugtracker'') de lazarus/free pascal], en el proyecto: "Lazarus Packages", Categoría<br />
"LazReport"; para remitir parches por favor, crea un informe de error y adjunta el parche al mismo.<br />
<br />
----</div>Mario13https://wiki.freepascal.org/index.php?title=LazReport_Documentation/es&diff=116758LazReport Documentation/es2018-03-29T14:19:17Z<p>Mario13: /* DOCUMENTACIÓN */</p>
<hr />
<div>{{LazReport Documentation}}[[category:Español|?]][[category:Castellano|?]]<br />
<br />
=PRESENTACIÓN=<br />
LazReport es un grupo de componentes que agregan a las aplicaciones la capacidad de generar reportes, usa un diseñador visual para crear reportes basados en bandas e incluye un mecanismo de reportes con previsualizador que ademas incluye un interprete para ejecutar guiones de usuario. El diseñador de reportes puede ser invocado en tiempo de ejecución<br />
<br />
=LINCENCIA=<br />
LazReport se origina en FreeReport 2.32 y gracias a la compañía Fast Reports Inc. esta disponible bajo la licencia LGPL modificada, la misma licencia que usa la libreria LCL de Lazarus. Para mayor información, vea los archivos lazreport/ license.txt, license-rus.txt y licence-lazreport.txt<br />
<br />
=AUTORES=<br />
FreeReport fué creado por la compañía Fast Reports Inc. <br />
La adaptación inicial del código a LazReport fue hecha por Olivier Guilbaud, para mayor infomación visite el sitio original de LazReport en SourceForge http://lazreport.sourceforge.net/.<br />
La integración en Lazarus y actual encargado del proyecto es Jesús Reyes Aguilar.<br />
LazReport no podría haber llegado a su estado actual sin la colaboración de muchos otros desarrolladores, vea el archivo lazreport/doc/contributors.txt<br />
<br />
=INSTALACIÓN=<br />
Para Instalar LazReport en Lazarus:<br />
<br />
# Abrir el paquete LazReport Package. Menú: Componentes->Abrir archivo de paquete (.lpk)...<br />
# Abrir archivo components/lazreport/source/lazreport.lpk<br />
# Instalar<br />
<br />
La siguiente vez que Lazarus sea iniciado, debería mostrar una separador LazReport en la paleta de componentes.<br />
<br />
=DOCUMENTACIÓN=<br />
El Manual del Desarrollador y La Guia del Usuario específicas para LazReport están aún por escribirse, mientras tanto, la mayoría de las funciones de LazReport están descritas en el Manual del Desarrollador de FreeReport (vea lazreport/doc/fr_eng.sxw en la instalción de Lazarus), Algunas cosas dependientes de la plataforma descritas allí, como objetos OLE, no están implementados en LazReport. También algunos ejemplos o imágenes hacen referencia a ejemplos que están disponibles solamente en Delphi.<br />
<br />
Hasta que la documentación especifica para LazReport sea elaborada, ésta página wiki será usada como repositorio de documentación, quizás en el futuro la documentación faltante pueda ser generada desde aquí. Se alienta a los usuarios a que agreguen temas que sientan haya necesidad de documentar, incluso si la descripción o contenido de dichos temas deba ser proporcionado por otros usuarios.<br />
<br />
== Operadores ==<br />
<br />
Los siguientes operadores están soportados:<br />
{| BORDER="1" CELLSPACING="0"<br />
!COLSPAN="1" STYLE="background:#ffdead;"|Tipo Operador<br />
!COLSPAN="1" STYLE="background:#ffdead;"|Operador<br />
|---- <br />
|Logicos||>, <, BUT, AND, NOT, =, < >, >=, <= <br />
|---- <br />
|Aritméticos||-, *, +, MOD, /<br />
|}<br />
<br />
==Funciones==<br />
Las siguientes funciones estás disponibles:<br />
===Funciones de agregación===<br />
;SUM(<X>) : Devuelve la suma de valores representados por <X>, que generalmente es un campo de datos. <br />
;AVG(<X>) : Devuelve el promedio de los valore de <X>.<br />
;COUNT : Cuenta la cantidad de ocurrencias.<br />
;MIN(<X>) : Devuelve le menor valor de todos los posibles valores de <X>.<br />
;MAX(<X>) : Devuelve le mayor valor de todos los posibles valores de <X>.<br />
<br />
===Funciones de formateo===<br />
;FORMATDATETIME(<X>, <Y>) : Devuelve una cadena con el valor <Y> (de tipo TDateTime) en el formato <X>. <X> usa la sintaxis default de los [http://www.freepascal.org/docs-html/rtl/sysutils/formatdatetime.html formatos de Lazarus].<br />
;FORMATFLOAT(<X>, <Y>) : Devuelve una cadena con el valor numérico <Y> en el formato <X>. <X> usa la sintaxis default de los [http://www.freepascal.org/docs-html/rtl/sysutils/formatfloat.html formatos de Lazarus].<br />
;STRTODATE(<X>) : Devuelve la representación en fecha (tipo TDateTime) de la cadena <X>. <X> debe estar formateada correctamente.<br />
;STRTOTIME(<X>) : Devuelve la representación en tiempo (tipo TDateTime) de la cadena <X>. <X> debe estar formateada correctamente.<br />
<br />
===Funciones de cadenas===<br />
;LOWERCASE(<X>) : Devuelve <X> pasada a minúsculas.<br />
;UPPERCASE(<X>) : Devuelve <X> pasada a mayúsculas.<br />
;NAMECASE(<X>) : Devuelve <X> con una mayúscula inicial en cada palabra.<br />
;COPY(<X>, <Y>, <Z>) : Es similar a la función "copy" de Pascal: devuelve la porción de la cadena <X> desde la posición <Y> contando <Z> letras. <br />
<br />
===Funciones Numéricas===<br />
;FRAC(<X>) : Devuelve la parte fraccionaria del número real <X>.<br />
;INT(<X>) : Devuelve la parte entera del número real <X>.<br />
;ROUND(<X>) : Devuelve el número real <X> redondeado al entero inmediato superior.<br />
;STR(<X>) : Devuelve una cadena representando al número <X>.<br />
<br />
===Logical/boolean functions===<br />
;IF(<X>, <Y>, <Z>) : Devuelve <Y> si la expresión <X> es verdadera. Si es falsa, devuelve <Z>.<br />
<br />
<br />
==Agregando tus propias funciones==<br />
Aunque probablemente no se necesite demasiado, LazReport te permite definir tus propias funciones. Ver [[LazReport Documentation#Documentation]] para las funciones ya existentes.<br />
Para agregar tus propias funciones:<br />
<br />
<br />
==Filtros de Exportación==<br />
Los filtros de exportación de LazReport se invocan usando el siguiente código.<br />
<source> if TheReport.PrepareReport then<br />
TheReport.ExportTo(TfrHTMExportFilter, 'exportedfile.html');</source><br />
Donde TheReport contiene una instancia del componente TfrReport. En este ejemplo se usa<br />
TfrHTMExportFilter para generar un archivo llamado 'exportedfile.html'. No es necesario preparar de nuevo el reporte si éste ha sido preparado con anterioridad. Para poder hacer uso de TfrHTMExportFilter el programador debe arrastrar y soltar un componente TfrHTMExportFilter desde el separador LazReport en la paleta de componentes, hacia el Diseñador de Formularios. Como una alternativa se puede añadir manualmente lr_e_htm a la clausula "uses" de la unidad.<br />
<br />
A partir de la versión 0.9.6 de LazReport el soporte de filtros de exportación ha sido mejorado, ahora los filtros de exportación pueden tomar parámetros que los usuarios pueden manipular ya sea cambiando los valores directamente o presentando al usuario final alguna interfaz de usuario. Para poder hacer cambios en los parametros, el programador debe crear un manipulador para el evento TfrReport.OnExportFilterSetup, disponible al seleccionar el componente TfrReport en el separador "Eventos" del Inspector de Objetos.<br />
<br />
El método manipulador del evento OnExportFilterSetup (de tipo TExportFilterSetup) toma un parámetro "sender" del tipo TfrExportFilter, para poder usar este tipo se debe añadir la unidad lr_class.pas a la clausula uses de la unidad. Todas la clases del tipo ExportFilter comparten este evento y el programador debe hacer un type-cast a la clase del filtro de exportación deseado, por ejemplo:<br />
<source> if sender is TfrHTMExportFilter then<br />
begin<br />
TfrHTMExportFilter(sender).UseCSS := false;<br />
end;</source><br />
A continuación una descripción de los filtros de exportación disponibles.<br />
<br />
===TfrExportFilter===<br />
&nbsp;&nbsp;&nbsp; Esta es la clase báse de todos los filtros de exportación, y defines dos propiedades que pueden ser modificadas por el desarrollador en el evento '''''OnExportFilterSetup''''':<br />
*'''BandTypes''': TfrBandTypes. Se trata de un conjunto de tipos de bandas, solo las bandas incluidas en este conjunto son efectivamente exportada, el resto de las bandas presentes en el informe se ignorarán. Usando esta propiedad un programador podría, por ejemplo, exportar sólo el contenido de la banda principal, dejando los títulos, encabezados y pies de página fuera de la salida exportada así:<br />
<source> sender.BandTypes := [btMasterData];</source><br />
de forma predeterminada, todas las bandas son procesadas pero ''TfrCSVExportFilter'' cambia esta propiedad para procesar únicamente la cabecera principal, las cabeceras de columna y las bandas principales de datos.<br />
*'''UseProgressbar''': boolean. Esta propiedad activa o desactiva la visualización de la barra de progreso del filtro de exportación. La propiedad tiene el valor predefinido como falso.<br />
<br />
===TfrTextExportFilter===<br />
&nbsp;&nbsp;&nbsp; Hereda de: TfrExportFilter <- TfrTextExportFilter<br>localizado en el archivo '''lr_e_txt.pas''' incluido en el paquete LazReport.<br />
<br />
&nbsp;&nbsp;&nbsp;Es la clase base de los filtros de texto. Este filtro de exportación trata de hacer una representación en texto de un informe gráfico mediante el ajuste de las coordenadas gráficas originales en una rejilla más gruesa donde cada unidad es un punto de la fuente ''UsedFont'', dependiendo del valor de ''UsedFont'', la salida exportada será más o menos parecida al diseño de objetos en el informe gráfico.<br />
<br />
&nbsp;&nbsp;&nbsp;Además de las propiedades heredadas de la clase TfrExportFilter, TfrTextExportFilter define dos propiedades más.<br />
*'''UsedFont''': integer. Esta propiedad define las dimensiones en puntos de la rejilla de salida, los objetos en el informe se colocan en esta red recalculando las posiciones x e y. El valor predeterminado es 10, si el usuario cambia este valor a 0 o menos, LazReport mostrará automáticamente un cuadro de diálogo preguntando por el valor UsedFont, si el usuario introduce un valor no válido, se utilizará el valor 10. Ee utiliza el valor 10 porque es el valor que mejor se adapta a los informes habituales que se hacen con las fuentes de 10-13 puntos.<br />
*'''UseBOM''': boolean. Esta propiedad permitirá la inclusión de caracteres UTF-8 con ''Byte Order Mark'' al comienzo de la salida de texto (ver [http://en.wikipedia.org/wiki/Byte_order_mark BOM]) que es requerido por algunos editores/visores, ya que BOM no se utiliza de forma predeterminada.<br />
<br />
===TfrCSVExportFilter===<br />
inheritance: TfrExportFilter <- TfrTextExportFilter <- TfrCSVExportFilter<br>located in: lr_e_csv.pas file included in LazReport package.<br />
<br />
This special text export filter produces Comma Separated Value output (actually any character can be used as separator), it differs from it's ancestor in that it doesn't try to create text layout representation of graphical report, instead, for each record output it tries to guess the fields order from the source report, it then produce a list of fields using a separator defined by the user. Beside the properties inherited from its ancestor classes it defines some properties to customize the generated output.<br />
*'''QuoteType''':TfrQuoteType. This property controls whether the generated field value should be wrapped using specified quote char or not. Possible values are ''qtNone'', ''qtQuoteChar'' and ''qtAutoQuote''. With ''qtNone'' the field value is never wrapped, ''qtQuoteChar'' will use the character specified by property '''QuoteChar''', any instance of '''QuoteChar''' already present in field value is duplicated. ''qtAutoQuote'' first try to find if any instance of '''separator''' or '''QuoteChar''' is already present in field value, if affirmative it behaves as if ''qtQuoteChar'' has been specified, on the contrary case, the field value is not wrapped just as if ''qtNone'' has been specified. '''QuoteType''' property is set to ''qtQuoteChar'' by default.<br />
*'''QuoteChar''':TUTF8Char. This holds the character to be used to wrap the field value in case of '''QuoteType''' of value ''qtQuoteChar'' has been specified or deduced if ''qtAutoQuote'' is set. Any instance of this character in the field value will be duplicated. by default '''QuoteChar''' is set to the " character.<br />
*'''Separator''':TUTF8Char. This is the character used to separate the fields in each record, by default is set to the ',' (COMMA) character but any UTF-8 valid character could be used. Some CSV files are actually TAB separated files, to get this, set Separator:=#9;<br />
The CSV exporter do not use the inherited UsedFont property value so any value set will be ignored. With default property values, TfrCSVExportFilter will produce Excel compatible files, the only caveat is that Excel will not recognize the file as UTF-8 encoded. To force Excel to recognize the encoding automatically, set the property '''UseBOM''' to true.<br />
===TfrHTMExportFilter===<br />
inheritance: TfrExportFilter <- TfrTextExportFilter <- TfrHTMExportFilter. <br> Located in: lr_e_htm.pas in LazReport package.<br />
<br />
This special text export filter produces valid "HTML 4.01 Transitional" output. Currently it defines only one additional property.<br />
*'''UseCSS''':boolean. This property controls whether or not the produced output include CSS information, this property is set to true by default.<br />
<br />
=INICIO RÁPIDO=<br />
==Reporte de Registros de un Dataset==<br />
En este ejemplo diseñaremos un reporte para imprimir registros desde un componente derivado de TDataset (TDbf, TSQLQuery, TZTable, TZQuery, Etcetera.). Primero se supone que LazReport ya esta instalado y que el componente dataset, llamado "Dbf1" aquí, ya esta configurado y activo. <br />
#Del separador LazReport en la paleta de componentes, seleccionamos el componente TfrReport y lo arrojamos en el Diseñador de Formularios, será nombrado automáticamente "frReport1".<br />
#Colocar también un componente TfrDbDataset, será nombrado "frDbDataset1"<br />
#Colocar un componente TButton, será nombrado "Button1", cambie su nombre a "btnShowReport"<br />
#Con el componente frDbDataset1 seleccionado, en el Inspector de Objectos seleccione "Dbf1" en la propiedad "Dataset"<br />
#Ahora seleccione frReport1 y usando el mismo procedimiento enlace su propiedad "Dataset" al componente "frDbDataset1":<p><center>[[Image:lrformsetup.png]]</center></p><br />
#Haga clic con el botón derecho sobre frReport1 y del menú seleccione "Diseñar Reporte". Se mostrará El Diseñador de Reportes de LazReport.<br />
#En la ventana del Diseñador de LazReport, seleccione el menu Herramientas->Herramientas->Insertar Campos DB. El diálogo "Insertar Campos" aparecerá.<br />
#En la lista de campos seleccione los campos que desee que aparezcan en el reporte<br />
#Seleccione las opciones "Incluir Encabezados" y "Incluir Bandas", el resultado debería ser similar a esto:<p><center>[[Image:lrinsertfieldsdialog.png]]</center></p><br />
#Presione el botón "Aceptar", LazReport colocara bandas y campos en el reporte de una formasimilar a la siguiente:<p><center>[[Image:lrreportwithfields.png]]</center></p><br />
#Presione el boton de Vista Previa [[Image:lrprevieweye.png]], LazReport mostrará entonces una vista previa del reporte:<p><center>[[Image:lrpreviewreport.png]]</center></p><br />
#Guarde el reporte usando el menú Archivos->Guardar, seleccione el mismo directorio del proyecto actual y guardelo como listing1.lrf<br />
#Cierre el Diseñador de Reportes.<br />
#Haga doble clic sobre el botón btnShowReport y teclee el siguiente código:<br />
<source> frReport1.LoadFromFile('listing1.lrf');<br />
frReport1.ShowReport;</source><br />
<br />
=Informar sobre errores=<br />
&nbsp;&nbsp;&nbsp;Por favor informa sobre los problemas utilizando el <br />
[http://www.freepascal.org/mantis/main_page.php seguimiento de errores (''bugtracker'') de lazarus/free pascal], en el proyecto: "Lazarus Packages", Categoría<br />
"LazReport"; para remitir parches por favor, crea un informe de error y adjunta el parche al mismo.<br />
<br />
----</div>Mario13https://wiki.freepascal.org/index.php?title=LazReport_Tutorial/pt&diff=116757LazReport Tutorial/pt2018-03-29T13:50:36Z<p>Mario13: /* Funções */</p>
<hr />
<div>{{LazReport Tutorial}}<br />
<br />
==Relatório==<br />
<br />
Vamos usar um demo de banco de dados fornecido pelo Delphi (alias DBDEMOS). Você deve criar uma nova aplicação com o formulário principal chamado Form1.<br />
<br />
Ponha no formulário os seguintes componentes:<br />
* TTable:<br />
* Table1.DataBaseName := DBDEMOS<br />
* Table1.TableName := ANIMALS.DBF<br />
* Table1.Active := TRUE<br />
* TDataSource<br />
* DataSource1.DataSet := Table1<br />
* TfrDBDataSet<br />
* frDbDataSet.DataSource := DataSource1<br />
* TfrReport<br />
* TfrDesigner<br />
* 2 TButton<br />
* Button1.Caption := ' Editing'<br />
* Button2.Caption := ' Preview'<br />
<br />
<br />
O que resulta em:<br />
<br />
[[Image:imagem1.jpg]]<br />
<br />
O LazReport permite associar nomes de variáveis a campos de dados ou valores do sistema, o que possibilita evitar que o usuário final decifre os geralmente pequenos nomes de campos. Em nosso exemplo vamos tentar criar uma variável nos campos BMP e NAME na Tabela1.<br />
<br />
[[Image:imagem2.jpg]]<br />
<br />
Clique em Variables Editor...<br />
<br />
[[Image:imagem3.jpg]]<br />
<br />
Agora clique no botão “Variables” para definir o lado esquerdo desta janela.<br />
<br />
[[Image:imagem4.jpg]]<br />
<br />
Escreva as sentenças conforme indicado na figura acima. Demo Variables representa a categoria e CampoXXXX as variáveis. Para diferenciar as duas, as variáveis começam com um espaço. Então clique em OK para ter o seguinte:<br />
<br />
[[Image:imagem5.jpg]]<br />
<br />
A categoria é disposta na ComboBox de variáveis acima. Cada variável precisa ser associada a um campo. Para isso, selecione a variável e depois o campo. A variável Name Field é associada ao campo Name da Tabela1.<br />
<br />
Como para as variáveis, clique com o botão direito do mouse no componente frReport e então em New State.<br />
Você abriu o editor:<br />
<br />
[[Image:imagem6.jpg]]<br />
<br />
Talvez você tenha notado um pequeno número de objetos na barra de objetos.<br />
<br />
[[Image:imagem7.jpg]]<br />
<br />
Deve ter visto que os objetos são iguais aos componentes QRLabel, QRMemo, etc, do QuickReport.<br />
<br />
[[Image:imagem8.jpg]]<br />
<br />
Em nosso relatório em branco você deve clicar no tipo de faixa que deseja criar:<br />
Selecione o título do estado e clique OK.<br />
<br />
{| BORDER="1" CELLSPACING="0"<br />
!COLSPAN="1" STYLE="background:#ffdead;"|Tipo de faixa<br />
!COLSPAN="1" STYLE="background:#ffdead;"|Uso<br />
|---- <br />
|Report title||Publicado apenas na primeira página<br />
|----<br />
|Report summary||Publicado apenas na última página<br />
|----<br />
|Page header||Publicado no topo de cada página<br />
|----<br />
|Page footer||Publicado no pé de cada página<br />
|----<br />
|Master header||Publicado no começo do primeiro nível (detalhe/barra)<br />
|----<br />
|Master Data||Dados do primeiro nível<br />
|----<br />
|Master Footer||Publicado no final do primeiro nível<br />
|----<br />
|Detail header||Publicado no começo do segundo nível (barra/detalhe)<br />
|----<br />
|Detail Data||Dados de segundo nível<br />
|----<br />
|Detail Footer||Publicado no final do segundo nível<br />
|----<br />
|Subdetail Header||Publicados no começo do terceiro (barra/detalhes)<br />
|----<br />
|Subdetail Data||Dados de terceiro nível<br />
|----<br />
|Subdetail Footer||Publicados no fim do terceiro nível<br />
|----<br />
|Overlay|| <br />
|----<br />
|Heading of column||Publicado no topo de cada coluna<br />
|----<br />
|Column base||Publicado no começo do grupo<br />
|----<br />
|Heading of group||Publicado no topo de cada página<br />
|----<br />
|Foot of group ||Publicado no final do grupo<br />
|----<br />
|VarColumn||Usado para tabelas cruzadas<br />
|}<br />
<br />
<br />
Nesta faixa, adicione um retângulo e o dimensione como quiser. Escolha uma cor para o plano de fundo com o botão Baldinho Cheio, então clique duas vezes no retângulo para indicar o título.<br />
<br />
[[Image:imagem9.jpg]]<br />
<br />
Na primeira linha deve ser indicado o título do relatório e na segunda, duas informações do sistema precisam ser adicionados. Eles são obtidos clicando em DB Field e depois em Other na ComboBox. Agora temos:<br />
<br />
[[Image:imagem10.jpg]]<br />
<br />
Vamos inserir a faixa como dados mestre, então clique duas vezes nessa faixa para selecionar frDBDataSet1, a principal fonte de dados do nosso exemplo.<br />
<br />
[[Image:imagem11.jpg]]<br />
<br />
Na metade esquerda da faixa insira um retângulo e dê um duplo clique.<br />
<br />
[[Image:imagem12.jpg]]<br />
<br />
Aqui podem ser colocados vários campos, mas pode ser mantido um retângulo para um único campo a fim de aplicar formatos, por exemplo. A primeira linha Name [Field Name] é obtida escrevendo-se Name e então, com o botão Variable, inserindo a variável [Field Name] (poderíamos ter escrito isto diretamente). Para a segunda linha, Size[[Table1, “SIZE”]*2.54], nós escrevemos Size e com o botão DB Field escolhemos o tamanho do campo de Table1 e para converter este campo, expresso em polegadas, para centímetros, multiplicamos este campo por 2.54. Pode-se ver o poder do fastreport. Com apenas um retângulo coloca-se em nosso estado, a segunda nomeação, dois campos, incluindo um calculado. Agora no lado direito da faixa selecione uma imagem. Para mostrar sempre a mesma figura, seria suficiente dar um duplo clique nessa figura e carregar a figura desejada. Nós queremos uma figura associada com o pressionamento da tecla F11, para mostrar o Inspetor de Objetos.<br />
<br />
[[Image:imagem13.jpg]]<br />
<br />
Informe a propriedade do Memo com a propriedade [ImageField]. Isso transforma a figura em um objeto associado com o campo de dados. O nosso primeiro estado está concluído. Deve ser gravado com o mesmo nome rapff. Um clique na pré-visualizaçao nos dá:<br />
<br />
[[Image:imagem14.jpg]] <br />
<br />
Agora vamos escrever o código necessário para carregar e visualizar ou editar o nosso relaltório rap1frf. Para isto adicione ao projeto o seguinte código:<br />
<br />
TForm1.Button2Click(Sender procedure: TObject); <br />
begin <br />
frReport1.LoadFromFile(' rap1.frf'); <br />
FrReport1.ShowReport; <br />
end;<br />
TForm1.ButtonClick(Sender procedure: TObject); <br />
begin <br />
frReport1.LoadFromFile(' rap1.frf'); <br />
frReport1.DesignReport; <br />
end; <br />
<br />
Você tem uma edição com pré-visualização que dá a possibilidade de os usuários finais modificarem o relatório sem precisar modificar a aplicação básica.<br />
<br />
Agora vamos adicionar funcionalidades ao nosso exemplo básico. Você deve adicionar um componente TButton com a propriedade Caption := ‘Print’; e um TPrintDialog. Obtemos isso:<br />
<br />
<br />
[[Image:imagem15.jpg]]<br />
<br />
Adicione também as unidades de impressora na cláusula uses do seu formulário e ponha o seguinte código no evento OnClick do botão Print:<br />
<br />
TForm1.bPrintClick(Sender procedure: TObject); <br />
var<br />
FromPg, ToPg, Cpy: Integer; <br />
ind: Integer; <br />
St: String; <br />
Collap: Boolean; <br />
begin <br />
/ / Carregar o estado<br />
St:=ExtractFilePath(ParamStr(0)); <br />
frReport1.LoadFromFile(St+' rap1.frf'); <br />
/ / Mudando a impressora padrão<br />
ind: = Printer.PrinterIndex; <br />
/ / Preparar o estado; para sair se a preparação não funcionar<br />
if not frReport1.PrepareReport then Exit; <br />
/ / inicializa a limpeza do diálogo para edição de parâmetros<br />
with PrintDialog1 C <br />
begin <br />
Options:=[poPageNums ]; / / autoriza a seleção de páginas<br />
Copies: = 1; / / apenas uma espécie<br />
Collate: = True; / / cópias ordenadas<br />
FromPage: = 1; / / página do começo<br />
ToPage: = frReport1.EMFPages.Count; // última página<br />
MaxPage: = frReport1.EMFPages.Count; / / número máximo de página<br />
if Execute then / / limpeza do diálogo <br />
begin <br />
if (Printer.PrinterIndex < > ind )/ / a impressora mudou? <br />
or frReport1.CanRebuild / / possui uma regeneração de estado? <br />
// mudança de impressora <br />
or frReport1.ChangePrinter(ind, Printer.PrinterIndex) then <br />
frReport1.PrepareReport <br />
else Exit; / / a mudança de impressora ocorreu de forma errônea <br />
if PrintDialog1.PrintRange = prPageNums then / / fez-se uma seleção de páginas<br />
begin <br />
FromPg : = PrintDialog1.FromPage; / / primeira página<br />
ToPg : = PrintDialog1.ToPage; / / última <br />
end; <br />
Cpy :=PrintDialog1.Copies; / / número de cópias <br />
Collap :=PrintDialog1.Collate; / / exemplares ordenados <br />
// recorte de edição da página FromPg com ToPg , " Cpy " <br />
// exemplares ordenados (Collap)) <br />
frReport1.PrintPreparedReport(FromPg, ToPg, Cpy, Collap); <br />
end; <br />
end; <br />
end;<br />
<br />
É um pouco longo mas nada impede que você crie uma classe herdada do TfrReport com um método de impressão ou, mais fácil, crie um procedimento PrintReport(letat: string) que carregue o relatório e o imprima.<br />
<br />
No menu Edit File > Page Options você obtém isso: <br />
<br />
[[Image:imagem24.jpg]]<br />
<br />
Para escolher o tamanho do papel<br />
<br />
[[Image:imagem16.jpg]]<br />
<br />
Para escolher as margens<br />
<br />
[[Image:imagem17.jpg]]<br />
<br />
Para especificar o número de colunas e o espaço entre as colunas.<br />
<br />
No menu principal do editor, selecione File > Report options para mostrar a seguinte caixa de diálogo:<br />
<br />
[[Image:imagem18.jpg]]<br />
<br />
Aqui você especifica a impressora necessária para o carregamento de estados e se a preparação é feita em duas formas.<br />
<br />
Se você quer numerar suas páginas com a página atual a partir do número total de páginas, você deve escolher a opção Two-pass Report.<br />
<br />
Aqui serão adicionadas ao nosso exemplo algumas variáveis não relacionadas aos dados. Elas tornarão possível, por exemplo, mostrar as diferentes nomeações de acordo com o contexto. Para isso, abra o editor de relatórios e selecione o menu File e a Lista de Variáveis. Com uma variável Test, como explicado anteriormente, a única diferença é que você não vai selecionar um campo de valor, mas deixar None (o valor padrão). Publique um dos objetos e adicione a variável Test como visto anteriormente. Retorne ao Delphi (não esquecer de salvar seu relatório) e publique o evento OnGetValue do componente FrRepor1 adicionando o seguinte código:<br />
<br />
procedure TForm1.frReport1GetValue(const ParName: String; <br />
var ParValue: Varying; VAr fld: TField); <br />
begin <br />
// trata o caso de variáveis não dependentes<br />
if UpperCase(ParName)=' TEST' then <br />
ParValue:=' Answer: Variable " test1 " '; <br />
end;<br />
<br />
Ou também é possível passar o valor diretamente para a variável através do seguinte código:<br />
<br />
procedure TForm1.Button1Click(Sender:TObject);<br />
begin<br />
frReport1.Values.FindVariable('test').Field := QuotedStr('test1');<br />
frReport1.ShowReport;<br />
end;<br />
<br />
<br />
Isto não é usado para os dados, mas para permitir formatar os dados com DisplayFormat.<br />
Agora vamos ver como criar uma variável calculada. Como antes, vamos criar uma nova categoria (opcional) e uma variável. Test Calculation. Selecione uma nova variável e escolha um valor da ComboBox " Other " e " Expression ". Essa seleção ativa a área de dados de entrada Expression. Escreva o seguinte: [Table1."SIZE"] + [Table1."WEIGHT"] . Dessa forma você obterá o sumário dos campos de dados Size e Weight. Você também pode colocar nome nas variáveis. E pode utilizar os seguintes operadores: <br />
<br />
{| BORDER="1" CELLSPACING="0"<br />
!COLSPAN="1" STYLE="background:#ffdead;"|Tipos de Operadores<br />
!COLSPAN="1" STYLE="background:#ffdead;"|Operadores<br />
|---- <br />
|Logic||>, <, BUT, AND, NOT, =, < >, > =, < = <br />
|---- <br />
|Mathematics||-, *, +, MOD, /<br />
|}<br />
<br />
Mais à frente você poderá dispor dos seguintes funções padronizadas:<br />
<br />
{| BORDER="1" CELLSPACING="0"<br />
!COLSPAN="1" STYLE="background:#ffdead;"|Função<br />
!COLSPAN="1" STYLE="background:#ffdead;"|Descrição<br />
!COLSPAN="1" STYLE="background:#ffdead;"|Exemplos<br />
|---- <br />
|SUM ||Soma|| <br />
|---- <br />
|AVG||Média|| <br />
|---- <br />
|MIN||Mínimo|| <br />
|---- <br />
|MAX||Máximo|| <br />
|---- <br />
|FORMATDATETIME||Data e hora formatadas|| <br />
|---- <br />
|FORMATFLOAT||Ponto flutuante formatado|| <br />
|---- <br />
|LOWERCASE||Letras minúsculas|| <br />
|---- <br />
|NAMECASE||Primeira maiúscula|| <br />
|---- <br />
|STRTODATE ||Data para string|| <br />
|---- <br />
|STRTOTIME||Hora para string|| <br />
|---- <br />
|UPPERCASE||Letras maiúsculas|| <br />
|}<br />
<br />
Se não for suficiente você pode criar suas próprias funções, mas isso nós veremos mais adiante.<br />
<br />
Agora vamos definir um formato para as variáveis de uma área. Um formato é válido para todas as variáveis de uma área de display. Para mostrar o editor de formatos, clique com o botão direito em uma área e então em Variable Format.<br />
<br />
[[Image:imagem19.jpg]]<br />
<br />
A primeira ComboBox indica o tipo de dado (texto, numérico, data, hora, lógico). A segunda permite selecionar o formato preestabelecido. O tipo Text não permite qualquer formatação e o tipo Number requer um número decimal com vírgula. A não ser para os tipos Text e Logic, você pode usar as funções de formatação do Delphi. Você pode incluir também o conceito de highlighting, que é muito útil para enfatizar dados. Você pode especificar uma condição para aplicar o highlighting. Para isso use a palavra-chave Value para indicar o valor da variável. Aqui é requisitado o highlighting para todos os valores maiores que 1000. Por padrão o highlighter é um simples negrito sobre fundo branco. Você pode definir esses parâmetros para uma área clicando no botão Realce.<br />
<br />
[[Image:imagem20.jpg]]<br />
<br />
Então você pode definir a cor do plano de fundo, o estilo e a cor da fonte a ser usada selecionando Intesified brightness.<br />
<br />
==Funções==<br />
<br />
É necessário adicionar ao arquivo FR.lng a linha seguinte:<br />
<br />
;FCT = CATEGORY | FCT(<X>, <Y>, <Z >) | Help on the function <br />
<br />
onde: <br />
FCT é o nome da função. CATEGORY, é o nome da categoria. FCT(<X>, <Y>, <Z >), é a visualização dos parâmetros necessários, com no máximo 3 parâmetros. Help., é uma pequena Ajuda que deve tornar possívell ao usuário entender o objetivo da função. | é um separador. <br />
Cada parâmetro é separado por vírgula e pode ser uma expressão, uma constante, uma variável, um campo ou dados.<br />
As constantes de tipo alfanumérico devem ser limitadas por um caractere. As variáveir são limitadas por and. Os campos de dados são limitados como as variáveis e tem o seguinte formato:<br />
<br />
;Dataset_Name. "Field_Name" <br />
<br />
Funções Estatísticas:<br />
<br />
;SUM(<X >) :. Retorna a soma dos valores dados por <X>, que é geralmente um campo de dados. <br />
;AVG(<X >) : Retorna a média dos valores dados por <X>.<br />
;COUNT : Meter. <br />
;MIN(<X >) : Retorna o valor mínimo dos valores dados em <X>. <br />
;MAX(<X >) : Retorna o valor máximo dos valores dados em <X >.<br />
<br />
===Funções nos dados:===<br />
;FORMATDATETIME(<X>, <Y >) : Retorna os dados abreviados em (TDateTime) < Y > no formato < X >. < X > usa a descrição padrão [https://www.freepascal.org/docs-html/rtl/sysutils/formatdatetime.html Lazarus para formatos].<br />
;FORMATFLOAT(<X>, <Y >) : Retorna o numeral < Y > no formato < X >. < X > usa o padrão de descrição [https://www.freepascal.org/docs-html/rtl/sysutils/formatfloat.html Lazarus para formatos].<br />
;STRTODATE(<X >) : Retorna a repesentação (TdateTime) da string < X >. < X > deve respeitar o formato de dados<br />
;STRTOTIME(<X >) : Retorna A representação digital (TDateTime) da string < X >. < X > deve respeitar o formato de horas.<br />
<br />
===Funções nos caracteres de conexão:===<br />
;LOWERCASE(<X >) : Retorna a string <X> em letras minúsculas.<br />
;UPPERCASE(<X >) : Retorna a string <X> em maiúsculas.<br />
;NAMECASE(<X >) :Retorna a string <X> com a primeira letra maiúscula.<br />
;COPY(<X>, <Y>, <Z >) :Retorna a string <X> na posição < Y > e comprimento< Z >. <br />
Funções nos numerais:<br />
;FRAC(<X >) : Retorna a parte decimal do número < X >. <br />
;INT(<X >) : Retorna a parte inteira do número < X >. <br />
;ROUND(<X >) : Retorna o número inteiro correspondente ao arredondamento de < X >. <br />
;STR(<X >) :Retorna a string correspondente de um número < X >.<br />
<br />
===Funções Lógicas:===<br />
;IF(<X>, <Y>, <Z >) : Retorna < Y > se a expresssão < X > é verdadeira, se falsa retorna < Z >.<br />
<br />
Para adicionar suas próprias funções é realmente muito simples. Aqui um código-fonte para adicionar as funções POS e SQRT:<br />
<br />
Unit FR_OGFct;<br />
interface <br />
implementation <br />
uses FR_Pars, FR_Class; / / Declaração-padrão<br />
type <br />
//Declaração de TBrOGFunctionLibrary <br />
TfrOGFunctionLibrary = class(TfrFunctionLibrary)<br />
public <br />
constructor Create; override; <br />
procedure DoFunction(FNo:integer procedure; p1, p2,<br />
p3:Variant; var valley:string); override; <br />
p3:Variant; var valley:string);<br />
end; <br />
//************************** / / * TfrOGFunctionLibrary <br />
constructor TfrOGFunctionLibrary.Create;<br />
begin <br />
inherited Create; <br />
with List do <br />
begin<br />
Add('POS');<br />
ADD('SQRT');<br />
end;<br />
end;<br />
Procedure TfrOGFunctionLibrary.DoFunction(FNo:Integer procedure; p1,<br />
p2, p3:Variant; Var valley:String);<br />
VAr Par1, Par2: Varying;<br />
Result: Variantying;<br />
begin<br />
Try<br />
Case FNo of //FNo é um íindice das funções declaradas no constructor <br />
0 : Begin //função POS <br />
Par1:=VarToStr(Parser.Calc(p1)); <br />
Par2:=VarToStr(Parser.Calc(P2)); <br />
Resultat:=Pos(Par1,Par2);<br />
end;<br />
1 : Resultat:=SQRT(Parser.Calc(P1)); //função SQRT<br />
end;<br />
Except <br />
// String resultante se der erro <br />
Resultat:='Erreur fonction '+List.Strings[FNo];<br />
end;<br />
Val:=VarToStr(Resultat); // String resultante<br />
end;<br />
Procedure DoInit;<br />
begin<br />
frRegisterFunctionLibrary(TfrOGFunctionLibrary);<br />
end;<br />
<br />
No arquivo FR.lng, anexe as seguintes linhas:<br />
<br />
;SQRT = Matemática e Trigonometria | SQRT(<X>) |Retorna a raiz quadrada de <X> <br />
;POS = Strings | POS(<X>,<Y>) Retorna a posição da string <X> em <Y> <br />
<br />
Publique um estado, então em File>List esta janela aparecerá:<br />
<br />
[[Image:imagem21.jpg]]<br />
<br />
Você pode notar o aparecimento de um pequeno botão (...), ativo somente se for o caso de uma expressão. Clique para abrir o editor abaixo:<br />
<br />
[[Image:imagem22.jpg]]<br />
<br />
Você pode notar a semelhança. Se clicar no botão Add você vai carregar o editor de parâmetros:<br />
<br />
[[Image:imagem23.jpg]]<br />
<br />
De acordo com o número de parâmetros, você terá mais ou menos zonas de edição. O botão (...) torna possível abrir o gerador de expressões para informar o parâmetro.<br />
<br />
----<br />
tradução: Ana Carolina Simplicio de Oliveira<br />
<br />
== See also ==<br />
* [[LazReport Tutorial]] English translation of this article<br />
<br />
[[Category:Lazarus/pt]]<br />
[[Category:LazReport/pt]]</div>Mario13https://wiki.freepascal.org/index.php?title=LazReport_Documentation&diff=116756LazReport Documentation2018-03-29T13:45:21Z<p>Mario13: /* Date functions */</p>
<hr />
<div>{{LazReport Documentation}}<br />
<br />
=Overview=<br />
LazReport is a group of components to add reporting capabilities to applications. It uses a visual designer to create banded reports and includes a report engine with previewer and an interpreter to run user scripts. The report designer can<br />
be invoked at runtime. <br />
<br />
=License=<br />
LazReport is based on FreeReport 2.32 and thanks to Fast Reports Inc. it's available under modified LGPL, the same license as the Lazarus LCL.<br />
See files lazreport/license.txt, license-rus.txt and license-lazreport.txt for details.<br />
<br />
=Authors=<br />
FreeReport was created for Fast Reports Inc.<br />
<br />
LazReport initial port was made by Olivier Guilbaud.<br />
<br />
Lazarus integration and fixes by Jesus Reyes A.<br />
<br />
Many contributors, see lazreport/doc/contributors.txt file<br />
<br />
=Install=<br />
To install LazReport in the Lazarus IDE:<br />
<br />
# Open LazReport Package. Menu: Components->Open package file (.lpk)...<br />
# Open file components/lazreport/source/lazreport.lpk<br />
# Install<br />
<br />
The next time Lazarus is started, it should show a LazReport tab in the component palette.<br />
<br />
=Documentation=<br />
Developer's manual and User Guides specific for LazReport are yet to be written. In the mean time, most LazReport features are described in the FreeReport Developer's Manual (see lazreport/doc/fr_eng.sxw in your Lazarus installation). Platform specific things described there like OLE objects are not implemented in LazReport, also some examples or pictures make reference to samples available only on Delphi. <br />
<br />
Until LazReport documentation is elaborated, this Wiki page will be used as a documentation container; maybe in the future the missing documentation could be generated from here. Users are welcomed to add topics that they feel need to be documented.<br />
<br />
==Operators==<br />
The following operators are supported:<br />
{| BORDER="1" CELLSPACING="0"<br />
!COLSPAN="1" STYLE="background:#ffdead;"|Operator type<br />
!COLSPAN="1" STYLE="background:#ffdead;"|Operators<br />
|---- <br />
|Logical||>, <, BUT, AND, NOT, =, < >, > =, < = <br />
|---- <br />
|Mathematical||-, *, +, MOD, /<br />
|}<br />
<br />
==Functions==<br />
The following functions are available for use:<br />
===Statistical functions===<br />
<br />
;SUM(<X >) : Returns the sum of values represented by <X>, which is generally a data field. <br />
;AVG(<X >) : Returns the average of <X> values.<br />
;COUNT : Count the number of occurrences.<br />
;MIN(<X >) : Returns the lowest value of all values represented by <X><br />
;MAX(<X >) : Returns the highest value of all values represented by <X><br />
<br />
===Date functions===<br />
{{Note|December 2013: inspection of lr_pars source code seems to indicate these functions work with the current locale date format, which limits interoperability. To do: verify this; extend function with an extra format parameter which defaults to e.g. ISO8601}}<br />
<br />
;FORMATDATETIME(<X>, <Y >) : Returns <Y> TDateTime in format <X>. <X> uses the default syntax for [http://www.freepascal.org/docs-html/rtl/sysutils/formatdatetime.html Lazarus formats].<br />
;FORMATFLOAT(<X>, <Y >) : Returns the numeric value <Y> in format <X>. <<X> uses the default syntax for [http://www.freepascal.org/docs-html/rtl/sysutils/formatfloat.html Lazarus formats].<br />
;STRTODATE(<X >) : Returns the TDateTime(? not date?) representation of string < X >. < X > must be formatted correctly.<br />
;STRTOTIME(<X >) : Returns the TDateTime time part representation of string < X >. < X > must be formatted correctly.<br />
<br />
===String functions:===<br />
;LOWERCASE(<X >) : Returns lowercase <X><br />
;UPPERCASE(<X >) : Returns uppercase <X><br />
;NAMECASE(<X >) : Returns <X> with initial capitals<br />
;COPY(<X>, <Y>, <Z >) : Similar to Pascal Copy: returns string <X> from position < Y > for < Z > characters. <br />
<br />
===Numeric functions===<br />
;FRAC(<X >) : Returns the decimal part of number < X ><br />
;INT(<X >) : Returns the integer part of number < X ><br />
;ROUND(<X >) : Returns the number < X > rounded to an integer (up? down? nearest integer? banker's rounding?)<br />
;STR(<X >) : Returns the string representation of number < X ><br />
<br />
===Logical/boolean functions===<br />
;IF(<X>, <Y>, <Z >) : Returns < Y > if expression < X > is true. If false, returns retorna < Z >.<br />
<br />
==Adding your own functions==<br />
Though it is probably not needed much, LazReport allows you to define your own functions. As mentioned, see [[LazReport Documentation#Documentation]] for an overview of existing functions.<br />
<br />
To add your own functions:<br />
<br />
=== Add template to definition file ===<br />
{{Note|This was taken from the Delphi/FastReport/FreeReport tutorial in Portuguese. It should be verified and probably modified to work with current Lazarus/LazReport}}<br />
<br />
You need to define your functions following the following template in the file FR.lng ('''is this still the correct name for Lazreprot?'''):<br />
<br />
, FCT = CATEGORY|FCT (<X> <Y>, <z>)|Help<br />
<br />
where:<br />
* FCT is the function name. <br />
* CATEGORY is the category name. <br />
* FCT (<X> <Y>, <z>), is the layout of the required parameters, with a maximum of 3 parameters. <br />
* Help Is a small help text which should allow the user to understand the purpose of the function. <br />
* | is a separator.<br />
<br />
Each parameter is separated by commas and can be an expression, a constant, a variable, a field or data.<br />
Alphanumeric type constants should be limited by a character. The variables are delimited by '''and'''.<br />
<br />
Data fields are limited to the variables and have the following format:<br />
;Dataset_Name. "Field_Name" <br />
<br />
Let's add the SQRT and POS functions by adding the following lines to '''FR.lng''' todo: still the same name?<br />
;SQRT = Mathematics and Trigonometry|SQRT(<X>)|Returns the square root of <X> <br />
;POS = Strings|POS(<X>,<Y>) Returns the position of string <X> within string <Y><br />
<br />
=== Add function source code ===<br />
A function definition is nice, but we haven't specified how these functions work. Therefore, some source code to add the functions POS and SQRT below:<br />
<syntaxhighlight><br />
Unit FR_OGFct;<br />
interface <br />
implementation <br />
uses FR_Pars, FR_Class; // Standard declarations needed for Lazreport!! Note: FR_pars etc? Are these names ok?<br />
type <br />
// Our own functions are declared here.<br />
TfrOGFunctionLibrary = class(TfrFunctionLibrary)<br />
public <br />
constructor Create; override; <br />
procedure DoFunction(FNo:integer procedure; p1, p2,<br />
p3:Variant; var valley:string); override; <br />
p3:Variant; var valley:string);<br />
end; <br />
//************************** <br />
// * TfrOGFunctionLibrary <br />
constructor TfrOGFunctionLibrary.Create;<br />
begin <br />
inherited Create; <br />
// Add our functions to the list of available functions:<br />
with List do <br />
begin<br />
Add('POS');<br />
Add('SQRT');<br />
end;<br />
end;<br />
<br />
Procedure TfrOGFunctionLibrary.DoFunction(FNo:Integer procedure; p1,<br />
p2, p3:Variant; Var valley:String); //valley?<br />
Var <br />
Par1, Par2: Varying;<br />
Result: Variantying; //variantying? variant?<br />
begin<br />
Try<br />
Case FNo of //this is the index of the functions as added in the constructor<br />
0 : <br />
begin // POS function<br />
Par1:=VarToStr(Parser.Calc(p1)); <br />
Par2:=VarToStr(Parser.Calc(P2)); <br />
Result:=Pos(Par1,Par2);<br />
end;<br />
1 : // SQRT function<br />
Result:=SQRT(Parser.Calc(P1));<br />
end;<br />
Except <br />
// String with error details<br />
Result:='Error in function '+List.Strings[FNo];<br />
end;<br />
Val:=VarToStr(Result); // Resulting string<br />
end;<br />
<br />
Procedure DoInit;<br />
begin<br />
frRegisterFunctionLibrary(TfrOGFunctionLibrary);<br />
end;<br />
</syntaxhighlight><br />
<br />
Save the report then File>List and this window will appear:<br />
<br />
[[Image:imagem21.jpg]]<br />
<br />
You may notice the appearance of a small (...) button, active only in the case of an expression. Click below to open the editor:<br />
<br />
[[Image:imagem22.jpg]]<br />
<br />
You may notice the similarity. If you click the Add button it will load the editor parameters:<br />
<br />
[[Image:imagem23.jpg]]<br />
<br />
Depending on the number of parameters, you have more or less edit areas. The (...) button makes it possible to open the expression generator to set the parameter.<br />
<br />
==Export Filters==<br />
LazReport has the ability to save the report displayed in the preview window using a user-defined format. It has an extension mechanism with support for plugins that can be used to add any amount of export filters. <br />
<br />
An export filter is a specially designed class which is registered in LazReport and allows you to save the report using one or more formats.<br />
<br />
When LazReport is installed, it includes some filters ready for use, these are: TfrTextExportFilter for exporting report as plain text, TfrCSVExportFilter used for exporting the report as CSV format and TfrHTMExportFilter for exporting the report as simple html file. Also included are some packages that provide additional filters, these are (see Menu Packages-> Install/De-Install packages...): lrCairoExport.lpk which provides support for exporting to PDF and PS formats by using the Cairo Graphics Library and lrExtExp.lpk with support for improved html export and some image formats like BMP, JPG and PNG. Also included in LazReport is the LazReportPDFExport.lpk package, this package provides PDF export using PowerPDF which is available in Lazarus-CCR repository.<br />
<br />
A filters package is installed in the same way as any other Lazarus Package; after restarting Lazarus, the filters (usually) appear as icons in the LazReport tab on the Component Palette.<br />
<br />
An export filter is added to your application by simply dragging one of these icons to a form or data module where TfrReport component exists, this is automatically registered and remains ready to use.<br />
<br />
This can also be done manually by including the export filter unit name in the Uses clause of the unit where TfrReport is used.<br />
<br />
LazReport export filters are invoked using one of two ways:<br />
#Save the report in the preview window. Using this method (pressing the save button) when the Save As dialog is presented, the user can choose a format from the list of registered formats. The list is populated by all registered export filters.<br />
#Through code using the TfrReport ExportTo method. See below for an example:<br />
<source><br />
if TheReport.PrepareReport then<br />
TheReport.ExportTo(TfrHTMExportFilter, 'exportedfile.html');<br />
</source><br />
Where TheReport holds an instance of TfrReport component. In this sample a TfrHTMExportFilter is used to generate a file named 'exportedfile.html'. It's not necessary to prepare the report again if it has been prepared previously.<br />
<br />
In order to use TfrHTMExportFilter the developer has to drag and drop an instance of the TfrHTMExportFilter component from the LazReport tab in the component palette to the form in the Form Designer. As an alternative the unit '''lr_e_htm.pas''' file can be added to the unit uses clause.<br />
<br />
Since LazReport 0.9.6, export filters support has been enhanced: now export filters can take parameters which users can customize either by changing values directly or by presenting the end user some UI. In order to make changes in parameters, the developer can create an event handler for TfrReport.OnExportFilterSetup event, available by selecting the TfrReport component and selecting the Events tab in Object Inspector.<br />
<br />
The OnExportFilterSetup (of type TExportFilterSetup) event handler takes an argument sender of type TfrExportFilter, in order to use this type, the '''lr_class.pas''' unit must be added to the unit uses clause. All ExportFilter clases share this event and the developer has to type-cast the sender argument to the desired export filter class, for example:<br />
<source><br />
if sender is TfrHTMExportFilter then<br />
begin<br />
TfrHTMExportFilter(sender).UseCSS := false;<br />
end;<br />
</source><br />
<br />
Below a description of available export filters.<br />
<br />
===TfrExportFilter=== <br />
is the base class of all export filters, and defines two properties that can be modified by the developer in the OnExportFilterSetup event:<br />
*'''BandTypes''': TfrBandTypes. this is a set of band types, only bands included in this set are actually exported; the other bands on the report will be ignored. Using this property a developer could for example export only the master band content, leaving titles, headers and footers out of exported output by doing:<br />
<source><br />
sender.BandTypes := [btMasterData];<br />
</source><br />
By default, all bands are processed but TfrCSVExportFilter changes this property to process only master header, column header and master data bands.<br />
*'''UseProgressbar''': boolean. This property enables or disables showing the progress bar while processing the export filter. This property is false by default.<br />
===TfrTextExportFilter===<br />
inheritance: TfrExportFilter <- TfrTextExportFilter<br>located in: '''lr_e_txt.pas''' file included with the LazReport package.<br />
<br />
is the base class of text based export filters. This export filter tries to make a text representation of a graphical report by fitting the original graphical coordinates into a more coarse grid where each unit is of "UsedFont" pixels, depending on the value of UsedFont value, the exported output may more or less represent the layout of objects in graphical report. Beside the properties inherited from TfrExportFilter class, TfrTextExportFilter define two more properties.<br />
*'''UsedFont''':integer. this property define the pixel dimensions on the output grid, objects on report are fitted into this grid by reclaculating each x and y position. The default value is 10, if user changes this value to 0 o less, LazReport will show automatically a dialog asking for the UsedFont value, if user enter a invalid value, a 10 value will be used. The 10 value is used because is the value that better fits the usual reports which are made with fonts 10-13 points.<br />
*'''UseBOM''':boolean. This property enable the inclusion of UTF-8 Byte Order Mark character at the start of text output (see [http://en.wikipedia.org/wiki/Byte_order_mark BOM]) needed by some editors/viewers, by default no BOM is used in exported output.<br />
===TfrCSVExportFilter===<br />
inheritance: TfrExportFilter <- TfrTextExportFilter <- TfrCSVExportFilter<br>located in: lr_e_csv.pas file included in LazReport package.<br />
<br />
This special text export filter produces Comma Separated Value output (actually any character can be used as separator), it differs from its ancestor in that it doesn't try to create text layout representation of graphical report, instead, for each record output it tries to guess the fields order from the source report, it then produce a list of fields using a separator defined by the user. Beside the properties inherited from its ancestor classes it defines some properties to customize the generated output.<br />
*'''QuoteType''':TfrQuoteType. This property controls whether the generated field value should be wrapped using specified quote char or not. Possible values are ''qtNone'', ''qtQuoteChar'' and ''qtAutoQuote''. With ''qtNone'' the field value is never wrapped, ''qtQuoteChar'' will use the character specified by property '''QuoteChar''', any instance of '''QuoteChar''' already present in field value is duplicated. ''qtAutoQuote'' first try to find if any instance of '''separator''' or '''QuoteChar''' is already present in field value, if affirmative it behaves as if ''qtQuoteChar'' has been specified, on the contrary case, the field value is not wrapped just as if ''qtNone'' has been specified. '''QuoteType''' property is set to ''qtQuoteChar'' by default.<br />
*'''QuoteChar''':TUTF8Char. This holds the character to be used to wrap the field value in case of '''QuoteType''' of value ''qtQuoteChar'' has been specified or deduced if ''qtAutoQuote'' is set. Any instance of this character in the field value will be duplicated. by default '''QuoteChar''' is set to the " character.<br />
*'''Separator''':TUTF8Char. This is the character used to separate the fields in each record, by default is set to the ',' (COMMA) character but any UTF-8 valid character could be used. Some CSV files are actually TAB separated files, to get this, set Separator:=#9;<br />
The CSV exporter do not use the inherited UsedFont property value so any value set will be ignored. With default property values, TfrCSVExportFilter will produce Excel compatible files, the only caveat is that Excel will not recognize the file as UTF-8 encoded. To force Excel to recognize the encoding automatically, set the property '''UseBOM''' to true.<br />
<br />
===TfrHTMExportFilter===<br />
inheritance: TfrExportFilter <- TfrTextExportFilter <- TfrHTMExportFilter. <br> Located in: lr_e_htm.pas in LazReport package.<br />
<br />
This special text export filter produces valid "HTML 4.01 Transitional" output. Currently it defines only one additional property.<br />
*'''UseCSS''':boolean. This property controls whether or not the produced output include CSS information, this property is set to true by default.<br />
<br />
==Script==<br />
A simple scripting language (interpreter) for a Pascal-like language is included in LazReport.<br />
<br />
Some notes:<br />
* the interpreter seems to expect semicolons after each line<br />
* the interpreter cannot handle nested if statements<br />
<br />
Example: this:<br />
<syntaxhighlight><br />
if [[PAY]>0] then begin<br />
if[[LATE_FEE]=1] then Text:=[MSGL2];<br />
else Text:= [MSGL1];<br />
end;<br />
</syntaxhighlight><br />
won't compile, while this will:<br />
<syntaxhighlight><br />
if[[LATE_FEE]=1] then Text:=[MSGL2];<br />
else Text:= [MSGL1];<br />
</syntaxhighlight><br />
<br />
Source: forum thread http://forum.lazarus.freepascal.org/index.php/topic,22902.0.html<br />
<br />
==Examples==<br />
You can find some examples in your Lazarus installation under components\lazreport\samples.<br />
<br />
=== Running total ===<br />
To calculate the total for values of each page added to the total on the previous page, follow these steps:<br />
* Make sure you have a report with a master data band connected to a dataset<br />
* Place a text inside that band and double click to open its editor.<br />
* In the editor, check the script option on the top left.<br />
* In the script window, paste the following code<br />
<syntaxhighlight><br />
IF [Line#] = 1 then RunTotal := [Dbf1."MTH_NO"]<br />
else RunTotal := RunTotal +[Dbf1."MTH_NO"]; <br />
</syntaxhighlight><br />
of course you need to replace [dbf1."MTH_NO"] with your field, the one you want a running total.<br />
* Click OK to save the changes.<br />
* Reopen the editor by double clicking on the text object<br />
* Click the "Variable" button.<br />
* Select the fr variables category in the drop down combo.<br />
* Double click the RunTotal variable to be placed on Memo.<br />
* Click OK and then press Preview.<br />
<br />
Source: {{MantisLink|17198}}<br />
<br />
==Tutorial==<br />
Please see [[LazReport Tutorial]].<br />
<br />
==See also==<br />
* [http://www.pp4s.co.uk/main/tu-db-firebird-demo3.html Creating and printing a report]<br />
<br />
=Report Designer=<br />
*Menu: File->Save As ... <br />
**Templates Notice:<br />
***While saving the current report, the user can select an arbitrary directory in the Save As dialog, in the case of templates (.lrt extension), the selected directory is ignored. Templates are always stored in the '''Templates Directory'''. The '''Templates Directory''' value can be set by either changing the frTemplateDir global variable (lr_desgn.pas unit) or by setting the TemplateDir property in a TfrDesigner component. The TemplateDir property will overwrite the frTemplateDir global variable if both are used. The '''Templates Directory''' can be an absolute path or a relative to program path directory, if this directory do not exists, LazReport will try to create it on the first use. If the TemplateDir property or the frTempateDir variable are not set, LazReport will try to save the templates in the program directory.<br />
***Binary templates format (.frt) is not recommended, as binary formats are hard to keep compatible with newer (or older) LazReport versions. If possible use .lrt file extension (XML file format).<br />
<br />
=Quick Start=<br />
==Report Records from a Dataset==<br />
In this sample we will design a report to print records from a dataset derived component (TDbf, TSQLQuery, TZTable, TZQuery, Etc.). First it's assumed that LazReport is already installed and the dataset component, called "Dbf1" here, is already configured and active. <br />
#From LazReport tab, select TfrReport component and drop it in Form Designer, it will be named "frReport1".<br />
#Drop a TfrDbDataset component, it will be named "frDbDataset1"<br />
#Drop a TButton, it will be named Button1, change its name to "btnShowReport"<br />
#With frDbDataset1 selected in Object Inspector select "Dbf1" for the "Dataset" property<br />
#Now select frReport1 and using the same procedure link its "Dataset" property to "frDbDataset1":<p><center>[[Image:lrformsetup.png]]</center></p><br />
#Right Click frReport1 and select "Design Report" from the menu, LazReport report designer will appear.<br />
#From Designer window, select menu Tools->Tools->Insert DB Fields, Insert fields Dialog will appear.<br />
#In field list select the fields you want in the report<br />
#Check "Include Headers" and "Include Bands" options, the result should be something like this:<p><center>[[Image:lrinsertfieldsdialog.png]]</center></p><br />
#Press the "Ok" button, LazReport will arrange bands and fields like this:<p><center> [[Image:lrreportwithfields.png]]</center></p><br />
#Press the preview button [[Image:lrprevieweye.png]], LazReport will then arrange things and show:<p><center>[[Image:lrpreviewreport.png]]</center></p><br />
#Save the report with Menu File->Save, select the same directory as the current project and name it as listing1.lrf<br />
#Close the report designer.<br />
#Double click btnShowReport and type the following code:<br />
<syntaxhighlight><br />
frReport1.LoadFromFile('listing1.lrf');<br />
frReport1.ShowReport;<br />
</syntaxhighlight><br />
<br />
=Bug reports=<br />
Please report problems using the <br />
[http://www.freepascal.org/mantis/main_page.php lazarus/freepascal bugtracker], project: "Lazarus Packages", Category<br />
"LazReport".<br />
<br />
For patches, please submit a bug report and attach the patch to it.<br />
<br />
[[Category:Components]]<br />
[[Category:Lazarus]]<br />
[[Category:LazReport]]</div>Mario13https://wiki.freepascal.org/index.php?title=ZeosDBO&diff=115511ZeosDBO2018-01-31T16:05:10Z<p>Mario13: /* SVN Version */</p>
<hr />
<div>{{ZeosDBO}}<br />
{{Infobox databases}}<br />
<br />
==About==<br />
ZeosDBO is a component suite to connect in various types of database (MySQL, Firebird, etc).<br />
<br />
==Screenshot==<br />
A screenshot of zeos components in lazarus component palette:<br />
<br />
[[Image:Zeos_access.png]]<br />
<br />
==Download==<br />
===Released Version===<br />
ZeosDBO can be found here http://sourceforge.net/projects/zeoslib.<br><br />
<br />
===SVN Version===<br />
These instructions will give you the trunk version of Zeos. You can also get the testing version; see the Zeos forum for details on differences.<br />
<br />
====Windows====<br />
* Install [http://tortoisesvn.tigris.org/ TortoiseSVN].<br />
* Create a new directory (example: C:\zeosdbo) to put the files and open this directory in Windows Explorer. <br />
* Right click inside directory and select '''SVN Checkout''' (popup menu). <br />
* Enter '''http://svn.code.sf.net/p/zeoslib/code-0/trunk''' in edit and press OK.<br />
<br />
====Linux====<br />
'''via esvn:''' <br />
* Install esvn: in terminal type: '''$ sudo apt-get install esvn'''<br />
* when finished, create a folder '''zeosdbo''' in your home dir: '''$ mkdir ~/zeosdbo'''<br />
* type '''$ esvn''' to run it in graphic mode, and so, menu file, select '''Checkout'''.<br />
* Enter '''http://svn.code.sf.net/p/zeoslib/code-0/trunk''' in '''URL''' edit and '''~/zeosdbo''' in '''Local Path'''<br />
* Edit and press '''OK'''<br />
<br />
'''via subversion:'''<br />
* first, install subversion: in terminal type: '''$ sudo apt-get install subversion'''<br />
* when finished, create a folder '''zeosdbo''' in your home dir: '''$ mkdir ~/zeosdbo'''<br />
* then access this folder '''$ cd ~/zeosdbo'''<br />
* type '''$ svn co http://svn.code.sf.net/p/zeoslib/code-0/trunk'''<br />
* later, if you want to update the repo, do '''$ cd ~/zeosdbo/trunk''' and '''$ svn update'''<br />
<br />
====Installing the SVN version in Lazarus====<br />
For all platforms, to install the SVN version into your Lazarus environment:<br />
* open Lazarus IDE<br />
* select packages/open package files (.lpk), then navigate to and open the file: packages/lazarus/'''zcomponent.lpk'''<br />
* click in the button "Compile" and wait for that process<br />
* click in the button "Use/install" (it will ask to rebuild the IDE, accept and continue)<br />
* After rebuilding the IDE, the new components will appear in the last tab "Zeos Access" of the Component Palette<br />
<br />
==Author==<br />
[http://zeos.firmos.at/ Zeos Team].<br />
<br />
==Bug report/Feature request==<br />
You can send bugs at [http://zeosbugs.firmos.at/ Zeos Bug Tracker].<br />
<br />
==External links==<br />
<br />
* [http://zeos.firmos.at/portal.php Zeos Web Site].<br />
* [http://zeos.firmos.at/index.php Zeos Web Forum].<br />
* [http://zeosdownloads.firmos.at/downloads/snapshots/ Zeos Snapshots].<br />
<br />
==See also==<br />
<br />
* [[Lazarus DB Faq]] - More about database programming<br />
* [[Getting Lazarus]] - Read them if you're a newbie in SVN...<br />
* [[Zeos tutorial]]<br />
<br/></div>Mario13https://wiki.freepascal.org/index.php?title=ZeosDBO&diff=115508ZeosDBO2018-01-31T15:54:46Z<p>Mario13: /* SVN Version */</p>
<hr />
<div>{{ZeosDBO}}<br />
{{Infobox databases}}<br />
<br />
==About==<br />
ZeosDBO is a component suite to connect in various types of database (MySQL, Firebird, etc).<br />
<br />
==Screenshot==<br />
A screenshot of zeos components in lazarus component palette:<br />
<br />
[[Image:Zeos_access.png]]<br />
<br />
==Download==<br />
===Released Version===<br />
ZeosDBO can be found here http://sourceforge.net/projects/zeoslib.<br><br />
<br />
===SVN Version===<br />
These instructions will give you the trunk version of Zeos. You can also get the testing version; see the Zeos forum for details on differences.<br />
<br />
====Windows====<br />
* Install [http://tortoisesvn.tigris.org/ TortoiseSVN].<br />
* Create a new directory (example: C:\zeosdbo) to put the files and open this directory in Windows Explorer. <br />
* Right click inside directory and select '''SVN Checkout''' (popup menu). <br />
* Enter '''http://svn.code.sf.net/p/zeoslib/code-0/trunk''' in edit and press OK.<br />
<br />
====Linux====<br />
'''via esvn:''' <br />
* Install esvn: in terminal type: '''$ sudo apt-get install esvn'''<br />
* when finished, create a folder '''zeosdbo''' in your home dir: '''$ mkdir ~/zeosdbo'''<br />
* type '''$ esvn''' to run it in graphic mode, and so, menu file, select '''Checkout'''.<br />
* Enter '''http://svn.code.sf.net/p/zeoslib/code-0/trunk''' in '''URL''' edit and '''~/zeosdbo''' in '''Local Path'''<br />
* Edit and press '''OK'''<br />
<br />
'''via subversion:'''<br />
* first, install subversion: in terminal type: '''$ sudo apt-get install subversion'''<br />
* when finished, create a folder '''zeosdbo''' in your home dir: '''$ mkdir ~/zeosdbo'''<br />
* then access this folder '''$ cd ~/zeosdbo'''<br />
* type '''$ svn co http://svn.code.sf.net/p/zeoslib/code-0/trunk'''<br />
* later, if you want to update the repo, do '''$ cd ~/zeosdbo/trunk''' and '''$ svn update'''<br />
<br />
====Installing the SVN version in Lazarus====<br />
For all platforms, to install the SVN version into your Lazarus environment:<br />
* open Lazarus IDE<br />
* select packages/open package files (.lpk), then navigate and open the '''zcomponent.lpk''' file<br />
* click in the button "Compile" and wait for that process<br />
* click in the button "Use/install" (it will ask to rebuild the IDE, accept and continue)<br />
* After rebuilding the IDE, the new components will appear in the last tab "Zeos Access" of the Component Palette<br />
<br />
==Author==<br />
[http://zeos.firmos.at/ Zeos Team].<br />
<br />
==Bug report/Feature request==<br />
You can send bugs at [http://zeosbugs.firmos.at/ Zeos Bug Tracker].<br />
<br />
==External links==<br />
<br />
* [http://zeos.firmos.at/portal.php Zeos Web Site].<br />
* [http://zeos.firmos.at/index.php Zeos Web Forum].<br />
* [http://zeosdownloads.firmos.at/downloads/snapshots/ Zeos Snapshots].<br />
<br />
==See also==<br />
<br />
* [[Lazarus DB Faq]] - More about database programming<br />
* [[Getting Lazarus]] - Read them if you're a newbie in SVN...<br />
* [[Zeos tutorial]]<br />
<br/></div>Mario13https://wiki.freepascal.org/index.php?title=ZeosDBO&diff=115507ZeosDBO2018-01-31T15:53:54Z<p>Mario13: /* Linux */</p>
<hr />
<div>{{ZeosDBO}}<br />
{{Infobox databases}}<br />
<br />
==About==<br />
ZeosDBO is a component suite to connect in various types of database (MySQL, Firebird, etc).<br />
<br />
==Screenshot==<br />
A screenshot of zeos components in lazarus component palette:<br />
<br />
[[Image:Zeos_access.png]]<br />
<br />
==Download==<br />
===Released Version===<br />
ZeosDBO can be found here http://sourceforge.net/projects/zeoslib.<br><br />
<br />
===SVN Version===<br />
These instructions will give you the trunk version of Zeos. You can also get the testing version; see the Zeos forum for details on differences.<br />
<br />
====Windows====<br />
* Install [http://tortoisesvn.tigris.org/ TortoiseSVN].<br />
* Create a new directory (example: C:\zeosdbo) to put the files and open this directory in Windows Explorer. <br />
* Right click inside directory and select '''SVN Checkout''' (popup menu). <br />
* Enter '''http://svn.code.sf.net/p/zeoslib/code-0/trunk''' in edit and press OK.<br />
<br />
====Linux====<br />
'''via esvn:''' <br />
* Install esvn: in terminal type: '''$ sudo apt-get install esvn'''<br />
* when finished, create a folder '''zeosdbo''' in your home dir: '''$ mkdir ~/zeosdbo'''<br />
* type '''$ esvn''' to run it in graphic mode, and so, menu file, select '''Checkout'''.<br />
* Enter '''http://svn.code.sf.net/p/zeoslib/code-0/trunk''' in '''URL''' edit and '''~/zeosdbo''' in '''Local Path'''<br />
* Edit and press '''OK'''<br />
<br />
'''via subversion:'''<br />
* first, install subversion: in terminal type: '''$ sudo apt-get install subversion'''<br />
* when finished, create a folder '''zeosdbo''' in your home dir: '''$ mkdir ~/zeosdbo'''<br />
* then access this folder '''$ cd ~/zeosdbo'''<br />
* type '''$ svn co http://svn.code.sf.net/p/zeoslib/code-0/trunk'''<br />
* later, if you want to update the repo, do '''$ cd ~/zeosdbo/trunk''' and '''$ svn update'''<br />
<br />
====Installing the SVN version in Lazarus====<br />
For all platforms, to install the SVN version into your Lazarus environment:<br />
* open Lazarus IDE<br />
* select packages/open package files (.lpk), then navigate and open the '''zcomponent.lpk''' file<br />
* click in the button "Compile" and wait to that process<br />
* click in the button "Use/install" (it will ask to rebuild the IDE, accept and continue)<br />
* After rebuilding the IDE, the new components will appear in the last tab "Zeos Access" of the Component Palette<br />
<br />
==Author==<br />
[http://zeos.firmos.at/ Zeos Team].<br />
<br />
==Bug report/Feature request==<br />
You can send bugs at [http://zeosbugs.firmos.at/ Zeos Bug Tracker].<br />
<br />
==External links==<br />
<br />
* [http://zeos.firmos.at/portal.php Zeos Web Site].<br />
* [http://zeos.firmos.at/index.php Zeos Web Forum].<br />
* [http://zeosdownloads.firmos.at/downloads/snapshots/ Zeos Snapshots].<br />
<br />
==See also==<br />
<br />
* [[Lazarus DB Faq]] - More about database programming<br />
* [[Getting Lazarus]] - Read them if you're a newbie in SVN...<br />
* [[Zeos tutorial]]<br />
<br/></div>Mario13https://wiki.freepascal.org/index.php?title=ZeosDBO&diff=115506ZeosDBO2018-01-31T15:53:08Z<p>Mario13: /* SVN Version */</p>
<hr />
<div>{{ZeosDBO}}<br />
{{Infobox databases}}<br />
<br />
==About==<br />
ZeosDBO is a component suite to connect in various types of database (MySQL, Firebird, etc).<br />
<br />
==Screenshot==<br />
A screenshot of zeos components in lazarus component palette:<br />
<br />
[[Image:Zeos_access.png]]<br />
<br />
==Download==<br />
===Released Version===<br />
ZeosDBO can be found here http://sourceforge.net/projects/zeoslib.<br><br />
<br />
===SVN Version===<br />
These instructions will give you the trunk version of Zeos. You can also get the testing version; see the Zeos forum for details on differences.<br />
<br />
====Windows====<br />
* Install [http://tortoisesvn.tigris.org/ TortoiseSVN].<br />
* Create a new directory (example: C:\zeosdbo) to put the files and open this directory in Windows Explorer. <br />
* Right click inside directory and select '''SVN Checkout''' (popup menu). <br />
* Enter '''http://svn.code.sf.net/p/zeoslib/code-0/trunk''' in edit and press OK.<br />
<br />
====Linux====<br />
'''via esvn''' <br />
* Install esvn: in terminal type: '''$ sudo apt-get install esvn'''<br />
* when finished, create a folder '''zeosdbo''' in your home dir: '''$ mkdir ~/zeosdbo'''<br />
* type '''$ esvn''' to run it in graphic mode, and so, menu file, select '''Checkout'''.<br />
* Enter '''http://svn.code.sf.net/p/zeoslib/code-0/trunk''' in '''URL''' edit and '''~/zeosdbo''' in '''Local Path'''<br />
* Edit and press '''OK'''<br />
<br />
'''via subversion:'''<br />
* first, instal subversion: in terminal type: '''$ sudo apt-get install subversion'''<br />
* when finished, create a folder '''zeosdbo''' in your home dir: '''$ mkdir ~/zeosdbo'''<br />
* then access this folder '''$ cd ~/zeosdbo'''<br />
* type '''$ svn co http://svn.code.sf.net/p/zeoslib/code-0/trunk'''<br />
* later, if you want to update the repo, do '''$ cd ~/zeosdbo/trunk''' and '''$ svn update'''<br />
<br />
====Installing the SVN version in Lazarus====<br />
For all platforms, to install the SVN version into your Lazarus environment:<br />
* open Lazarus IDE<br />
* select packages/open package files (.lpk), then navigate and open the '''zcomponent.lpk''' file<br />
* click in the button "Compile" and wait to that process<br />
* click in the button "Use/install" (it will ask to rebuild the IDE, accept and continue)<br />
* After rebuilding the IDE, the new components will appear in the last tab "Zeos Access" of the Component Palette<br />
<br />
==Author==<br />
[http://zeos.firmos.at/ Zeos Team].<br />
<br />
==Bug report/Feature request==<br />
You can send bugs at [http://zeosbugs.firmos.at/ Zeos Bug Tracker].<br />
<br />
==External links==<br />
<br />
* [http://zeos.firmos.at/portal.php Zeos Web Site].<br />
* [http://zeos.firmos.at/index.php Zeos Web Forum].<br />
* [http://zeosdownloads.firmos.at/downloads/snapshots/ Zeos Snapshots].<br />
<br />
==See also==<br />
<br />
* [[Lazarus DB Faq]] - More about database programming<br />
* [[Getting Lazarus]] - Read them if you're a newbie in SVN...<br />
* [[Zeos tutorial]]<br />
<br/></div>Mario13https://wiki.freepascal.org/index.php?title=ZeosDBO&diff=115505ZeosDBO2018-01-31T15:41:07Z<p>Mario13: /* Linux */</p>
<hr />
<div>{{ZeosDBO}}<br />
{{Infobox databases}}<br />
<br />
==About==<br />
ZeosDBO is a component suite to connect in various types of database (MySQL, Firebird, etc).<br />
<br />
==Screenshot==<br />
A screenshot of zeos components in lazarus component palette:<br />
<br />
[[Image:Zeos_access.png]]<br />
<br />
==Download==<br />
===Released Version===<br />
ZeosDBO can be found here http://sourceforge.net/projects/zeoslib.<br><br />
<br />
===SVN Version===<br />
These instructions will give you the trunk version of Zeos. You can also get the testing version; see the Zeos forum for details on differences.<br />
<br />
====Windows====<br />
* Install [http://tortoisesvn.tigris.org/ TortoiseSVN].<br />
* Create a new directory (example: C:\zeosdbo) to put the files and open this directory in Windows Explorer. <br />
* Right click inside directory and select '''SVN Checkout''' (popup menu). <br />
* Enter '''http://svn.code.sf.net/p/zeoslib/code-0/trunk''' in edit and press OK.<br />
<br />
====Linux====<br />
'''via esvn''' <br />
* Install esvn: in terminal type: '''$ sudo apt-get install esvn'''<br />
* when finished, create a folder '''zeosdbo''' in your home dir: '''$ mkdir ~/zeosdbo'''<br />
* type '''$ esvn''' to run it in graphic mode, and so, menu file, select '''Checkout'''.<br />
* Enter '''http://svn.code.sf.net/p/zeoslib/code-0/trunk''' in '''URL''' edit and '''~/zeosdbo''' in '''Local Path'''<br />
* Edit and press '''OK'''<br />
<br />
<br />
'''via subversion:'''<br />
* first, instal subversion: in terminal type: '''$ sudo apt-get install subversion'''<br />
* when finished, create a folder '''zeosdbo''' in your home dir: '''$ mkdir ~/zeosdbo'''<br />
* then access this folder '''$ cd ~/zeosdbo'''<br />
* type '''$ svn co http://svn.code.sf.net/p/zeoslib/code-0/trunk'''<br />
* later, if you want to update the repo, do '''$ cd ~/zeosdbo/trunk''' and '''$ svn update'''<br />
<br />
====Installing the SVN version in Lazarus====<br />
For all platforms, to install the SVN version into your Lazarus environment:<br />
* open Lazarus<br />
* in the IDE select packages/open package files (.lpk), then open the zcomponent.lpk file, click compile and then click use/install.<br />
<br />
==Author==<br />
[http://zeos.firmos.at/ Zeos Team].<br />
<br />
==Bug report/Feature request==<br />
You can send bugs at [http://zeosbugs.firmos.at/ Zeos Bug Tracker].<br />
<br />
==External links==<br />
<br />
* [http://zeos.firmos.at/portal.php Zeos Web Site].<br />
* [http://zeos.firmos.at/index.php Zeos Web Forum].<br />
* [http://zeosdownloads.firmos.at/downloads/snapshots/ Zeos Snapshots].<br />
<br />
==See also==<br />
<br />
* [[Lazarus DB Faq]] - More about database programming<br />
* [[Getting Lazarus]] - Read them if you're a newbie in SVN...<br />
* [[Zeos tutorial]]<br />
<br/></div>Mario13https://wiki.freepascal.org/index.php?title=Add_Help_to_Your_Application&diff=83196Add Help to Your Application2014-09-24T19:43:05Z<p>Mario13: /* Creating a help entry */</p>
<hr />
<div>{{Add Help to Your Application}}<br />
<br />
The LCL comes with a help system, and allows you to create help for your own applications.<br />
<br />
== Quick Start ==<br />
<br />
Open the example in examples/helphtml/.<br />
<br />
This project demonstrates how to use the HTML help components. Just drop them on a form of your project. Setup the paths and create some HTML pages. Then give each control of your application a HelpKeyword.<br />
<br />
See the CHM help section if you want to use CHM help files instead of HTML help files.<br />
<br />
== Help Basics ==<br />
<br />
The LCL help mainly consists of two parts: Help databases and help viewers. A Help Database contains the mapping from the keywords (ID, node, message, pascal, ...) to the help page (or help web site or...). The Help Viewer is invoked by the Help Database to show the help to the user.<br />
<br />
*A THelpDatabase manages content. It can be a collection of HTML pages or fpdoc XML files or a CHM file or a database or whatever. <br />
*A THelpViewer is a component that shows help content. For example a viewer for the mime type text/html can start a web browser.<br />
<br />
When help is requested, the LCL queries each registered THelpDatabase and each database can return a list of entries.<br />
If several entries are returned, the LCL asks the user to choose an entry.<br />
Then the LCL asks the database to show the help for the entry. The database extracts the help content and asks the LCL for a viewer that supports the mime type of the content.<br />
Finally, the viewer shows the help content.<br />
<br />
== CHM ==<br />
Context-sensitive CHM application help can be used from Lazarus 1.0 and later.<br />
<br />
A demonstration program is included that shows how to include context-sensitive help using CHM and the lhelp CHM viewer (the same one that is used for IDE help by default).<br />
Please see ${lazarusdir}/components/chmhelp/democontrol/.<br />
<br />
You can write your own CHM files, e.g. with the now ancient Microsoft HTML Workshop or with the new Lazarus chmmaker tools in $(lazarusdir)/tools/chmmaker<br />
You can use a CHMHelpDatabase control like the HTMLHelpdatabase control described below.<br />
<br />
The advantages of using the CHM system are a smaller, self contained help file instead of multiple files. On the other hand, not every system has a CHM viewer installed by default, so you might want to include lhelp, a CHM viewer written in Pascal and included with the Lazarus sources (components/chmhelp/lhelp/lhelp.lpi).<br />
<br />
== HTML ==<br />
<br />
The LCL provides two components to use HTML files for help: THTMLHelpDatabase and THTMLBrowserHelpViewer.<br />
To see the HTML help, see the lazarus example examples/helphtml/htmlhelp1.lpi.<br />
<br />
=== Setup HTML help for your application ===<br />
<br />
Adding HTML help to your application is easy:<br />
[[File:LazHtmlHelp.jpg|500px|thumb|right|Lazarus help items]] <br />
*Put a '''THTMLHelpDatabase''' on a form.<br />
*Set '''AutoRegister''' to true.<br />
*Set '''KeywordPrefix''' to '''html/'''. It means all keywords must start with the string ''html/''.<br />
*Set '''BaseURL''' to '''file://yourhelp/'''. This will search the HTML files in the sub folder ''yourhelp''. You can specify full paths like ''file:///usr/lib/yourhelp/'' or an URL like ''http://www.yoursite.com/''. <br />
<br />
*Put a '''THTMLBrowserHelpViewer''' on the form. This component can start the user's default browser.<br />
*Set '''AutoRegister''' to true.<br />
<br />
=== Creating a help entry ===<br />
<br />
*Now create the subfolder ''yourhelp'' and create a html page ''yourhelp/edit1.html''. In case of a website, the help page should be accesible as ''http://www.yoursite.com/edit1.html''<br />
*Put a TEdit on a form.<br />
*Set '''HelpType''' to ''htKeyword''<br />
*Set '''HelpKeyword''' to ''html/edit1.html''<br />
<br />
When running the program you can focus the edit and press F1 to invoke the help. Under OS X the help key is Cmd-? (or Cmd+Shift+? depending on you keyboard layout).<br />
Note: Some window managers, widget set combinations do not pass F1 to the LCL.<br />
<br />
[[Category:Tutorials]]<br />
[[Category:Help and Docs]]<br />
[[Category:CHM]]</div>Mario13https://wiki.freepascal.org/index.php?title=Add_Help_to_Your_Application&diff=83195Add Help to Your Application2014-09-24T19:40:53Z<p>Mario13: /* Setup HTML help for your application */</p>
<hr />
<div>{{Add Help to Your Application}}<br />
<br />
The LCL comes with a help system, and allows you to create help for your own applications.<br />
<br />
== Quick Start ==<br />
<br />
Open the example in examples/helphtml/.<br />
<br />
This project demonstrates how to use the HTML help components. Just drop them on a form of your project. Setup the paths and create some HTML pages. Then give each control of your application a HelpKeyword.<br />
<br />
See the CHM help section if you want to use CHM help files instead of HTML help files.<br />
<br />
== Help Basics ==<br />
<br />
The LCL help mainly consists of two parts: Help databases and help viewers. A Help Database contains the mapping from the keywords (ID, node, message, pascal, ...) to the help page (or help web site or...). The Help Viewer is invoked by the Help Database to show the help to the user.<br />
<br />
*A THelpDatabase manages content. It can be a collection of HTML pages or fpdoc XML files or a CHM file or a database or whatever. <br />
*A THelpViewer is a component that shows help content. For example a viewer for the mime type text/html can start a web browser.<br />
<br />
When help is requested, the LCL queries each registered THelpDatabase and each database can return a list of entries.<br />
If several entries are returned, the LCL asks the user to choose an entry.<br />
Then the LCL asks the database to show the help for the entry. The database extracts the help content and asks the LCL for a viewer that supports the mime type of the content.<br />
Finally, the viewer shows the help content.<br />
<br />
== CHM ==<br />
Context-sensitive CHM application help can be used from Lazarus 1.0 and later.<br />
<br />
A demonstration program is included that shows how to include context-sensitive help using CHM and the lhelp CHM viewer (the same one that is used for IDE help by default).<br />
Please see ${lazarusdir}/components/chmhelp/democontrol/.<br />
<br />
You can write your own CHM files, e.g. with the now ancient Microsoft HTML Workshop or with the new Lazarus chmmaker tools in $(lazarusdir)/tools/chmmaker<br />
You can use a CHMHelpDatabase control like the HTMLHelpdatabase control described below.<br />
<br />
The advantages of using the CHM system are a smaller, self contained help file instead of multiple files. On the other hand, not every system has a CHM viewer installed by default, so you might want to include lhelp, a CHM viewer written in Pascal and included with the Lazarus sources (components/chmhelp/lhelp/lhelp.lpi).<br />
<br />
== HTML ==<br />
<br />
The LCL provides two components to use HTML files for help: THTMLHelpDatabase and THTMLBrowserHelpViewer.<br />
To see the HTML help, see the lazarus example examples/helphtml/htmlhelp1.lpi.<br />
<br />
=== Setup HTML help for your application ===<br />
<br />
Adding HTML help to your application is easy:<br />
[[File:LazHtmlHelp.jpg|500px|thumb|right|Lazarus help items]] <br />
*Put a '''THTMLHelpDatabase''' on a form.<br />
*Set '''AutoRegister''' to true.<br />
*Set '''KeywordPrefix''' to '''html/'''. It means all keywords must start with the string ''html/''.<br />
*Set '''BaseURL''' to '''file://yourhelp/'''. This will search the HTML files in the sub folder ''yourhelp''. You can specify full paths like ''file:///usr/lib/yourhelp/'' or an URL like ''http://www.yoursite.com/''. <br />
<br />
*Put a '''THTMLBrowserHelpViewer''' on the form. This component can start the user's default browser.<br />
*Set '''AutoRegister''' to true.<br />
<br />
=== Creating a help entry ===<br />
<br />
*Now create the sub folder ''html'' and create a html page ''html/edit1.html''.<br />
*Put a TEdit on a form.<br />
*Set '''HelpType''' to ''htKeyword''<br />
*Set '''HelpKeyword''' to ''html/edit1.html''<br />
<br />
When running the program you can focus the edit and press F1 to invoke the help. Under OS X the help key is Cmd-? (or Cmd+Shift+? depending on you keyboard layout).<br />
Note: Some window managers, widget set combinations do not pass F1 to the LCL.<br />
<br />
[[Category:Tutorials]]<br />
[[Category:Help and Docs]]<br />
[[Category:CHM]]</div>Mario13https://wiki.freepascal.org/index.php?title=Add_Help_to_Your_Application&diff=83194Add Help to Your Application2014-09-24T19:32:44Z<p>Mario13: /* Setup HTML help for your application */</p>
<hr />
<div>{{Add Help to Your Application}}<br />
<br />
The LCL comes with a help system, and allows you to create help for your own applications.<br />
<br />
== Quick Start ==<br />
<br />
Open the example in examples/helphtml/.<br />
<br />
This project demonstrates how to use the HTML help components. Just drop them on a form of your project. Setup the paths and create some HTML pages. Then give each control of your application a HelpKeyword.<br />
<br />
See the CHM help section if you want to use CHM help files instead of HTML help files.<br />
<br />
== Help Basics ==<br />
<br />
The LCL help mainly consists of two parts: Help databases and help viewers. A Help Database contains the mapping from the keywords (ID, node, message, pascal, ...) to the help page (or help web site or...). The Help Viewer is invoked by the Help Database to show the help to the user.<br />
<br />
*A THelpDatabase manages content. It can be a collection of HTML pages or fpdoc XML files or a CHM file or a database or whatever. <br />
*A THelpViewer is a component that shows help content. For example a viewer for the mime type text/html can start a web browser.<br />
<br />
When help is requested, the LCL queries each registered THelpDatabase and each database can return a list of entries.<br />
If several entries are returned, the LCL asks the user to choose an entry.<br />
Then the LCL asks the database to show the help for the entry. The database extracts the help content and asks the LCL for a viewer that supports the mime type of the content.<br />
Finally, the viewer shows the help content.<br />
<br />
== CHM ==<br />
Context-sensitive CHM application help can be used from Lazarus 1.0 and later.<br />
<br />
A demonstration program is included that shows how to include context-sensitive help using CHM and the lhelp CHM viewer (the same one that is used for IDE help by default).<br />
Please see ${lazarusdir}/components/chmhelp/democontrol/.<br />
<br />
You can write your own CHM files, e.g. with the now ancient Microsoft HTML Workshop or with the new Lazarus chmmaker tools in $(lazarusdir)/tools/chmmaker<br />
You can use a CHMHelpDatabase control like the HTMLHelpdatabase control described below.<br />
<br />
The advantages of using the CHM system are a smaller, self contained help file instead of multiple files. On the other hand, not every system has a CHM viewer installed by default, so you might want to include lhelp, a CHM viewer written in Pascal and included with the Lazarus sources (components/chmhelp/lhelp/lhelp.lpi).<br />
<br />
== HTML ==<br />
<br />
The LCL provides two components to use HTML files for help: THTMLHelpDatabase and THTMLBrowserHelpViewer.<br />
To see the HTML help, see the lazarus example examples/helphtml/htmlhelp1.lpi.<br />
<br />
=== Setup HTML help for your application ===<br />
<br />
Adding HTML help to your application is easy:<br />
[[File:LazHtmlHelp.jpg|500px|thumb|right|Lazarus help items]] <br />
*Put a '''THTMLHelpDatabase''' on a form.<br />
*Set '''AutoRegister''' to true.<br />
*Set '''KeywordPrefix''' to '''html/'''. It means all keywords must start with the string ''html/''.<br />
*Set '''BaseURL''' to '''file://html/'''. This will search the HTML files in the sub folder ''html''. You can specify full paths like ''file:///usr/lib/yourhelp/'' or an URL like ''http://www.yoursite.com/''. In the later case, the help page should be accesible as ''http://www.yoursite.com/edit1.html''<br />
<br />
*Put a '''THTMLBrowserHelpViewer''' on the form. This component can start the user's default browser.<br />
*Set '''AutoRegister''' to true.<br />
<br />
=== Creating a help entry ===<br />
<br />
*Now create the sub folder ''html'' and create a html page ''html/edit1.html''.<br />
*Put a TEdit on a form.<br />
*Set '''HelpType''' to ''htKeyword''<br />
*Set '''HelpKeyword''' to ''html/edit1.html''<br />
<br />
When running the program you can focus the edit and press F1 to invoke the help. Under OS X the help key is Cmd-? (or Cmd+Shift+? depending on you keyboard layout).<br />
Note: Some window managers, widget set combinations do not pass F1 to the LCL.<br />
<br />
[[Category:Tutorials]]<br />
[[Category:Help and Docs]]<br />
[[Category:CHM]]</div>Mario13https://wiki.freepascal.org/index.php?title=Add_Help_to_Your_Application&diff=83193Add Help to Your Application2014-09-24T19:27:54Z<p>Mario13: /* Setup HTML help for your application */</p>
<hr />
<div>{{Add Help to Your Application}}<br />
<br />
The LCL comes with a help system, and allows you to create help for your own applications.<br />
<br />
== Quick Start ==<br />
<br />
Open the example in examples/helphtml/.<br />
<br />
This project demonstrates how to use the HTML help components. Just drop them on a form of your project. Setup the paths and create some HTML pages. Then give each control of your application a HelpKeyword.<br />
<br />
See the CHM help section if you want to use CHM help files instead of HTML help files.<br />
<br />
== Help Basics ==<br />
<br />
The LCL help mainly consists of two parts: Help databases and help viewers. A Help Database contains the mapping from the keywords (ID, node, message, pascal, ...) to the help page (or help web site or...). The Help Viewer is invoked by the Help Database to show the help to the user.<br />
<br />
*A THelpDatabase manages content. It can be a collection of HTML pages or fpdoc XML files or a CHM file or a database or whatever. <br />
*A THelpViewer is a component that shows help content. For example a viewer for the mime type text/html can start a web browser.<br />
<br />
When help is requested, the LCL queries each registered THelpDatabase and each database can return a list of entries.<br />
If several entries are returned, the LCL asks the user to choose an entry.<br />
Then the LCL asks the database to show the help for the entry. The database extracts the help content and asks the LCL for a viewer that supports the mime type of the content.<br />
Finally, the viewer shows the help content.<br />
<br />
== CHM ==<br />
Context-sensitive CHM application help can be used from Lazarus 1.0 and later.<br />
<br />
A demonstration program is included that shows how to include context-sensitive help using CHM and the lhelp CHM viewer (the same one that is used for IDE help by default).<br />
Please see ${lazarusdir}/components/chmhelp/democontrol/.<br />
<br />
You can write your own CHM files, e.g. with the now ancient Microsoft HTML Workshop or with the new Lazarus chmmaker tools in $(lazarusdir)/tools/chmmaker<br />
You can use a CHMHelpDatabase control like the HTMLHelpdatabase control described below.<br />
<br />
The advantages of using the CHM system are a smaller, self contained help file instead of multiple files. On the other hand, not every system has a CHM viewer installed by default, so you might want to include lhelp, a CHM viewer written in Pascal and included with the Lazarus sources (components/chmhelp/lhelp/lhelp.lpi).<br />
<br />
== HTML ==<br />
<br />
The LCL provides two components to use HTML files for help: THTMLHelpDatabase and THTMLBrowserHelpViewer.<br />
To see the HTML help, see the lazarus example examples/helphtml/htmlhelp1.lpi.<br />
<br />
=== Setup HTML help for your application ===<br />
<br />
Adding HTML help to your application is easy:<br />
[[File:LazHtmlHelp.jpg|500px|thumb|right|Lazarus help items]] <br />
*Put a '''THTMLHelpDatabase''' on a form.<br />
*Set '''AutoRegister''' to true.<br />
*Set '''KeywordPrefix''' to '''html/'''. It means all keywords must start with the string ''HTML/''.<br />
*Set '''BaseURL''' to '''file://html/'''. This will search the HTML files in the sub folder ''html''. You can specify full paths like ''file:///usr/lib/yourhelp/'' or an URL like ''http://www.yoursite.com/''.<br />
<br />
*Put a '''THTMLBrowserHelpViewer''' on the form. This component can start the user's default browser.<br />
*Set '''AutoRegister''' to true.<br />
<br />
=== Creating a help entry ===<br />
<br />
*Now create the sub folder ''html'' and create a html page ''html/edit1.html''.<br />
*Put a TEdit on a form.<br />
*Set '''HelpType''' to ''htKeyword''<br />
*Set '''HelpKeyword''' to ''html/edit1.html''<br />
<br />
When running the program you can focus the edit and press F1 to invoke the help. Under OS X the help key is Cmd-? (or Cmd+Shift+? depending on you keyboard layout).<br />
Note: Some window managers, widget set combinations do not pass F1 to the LCL.<br />
<br />
[[Category:Tutorials]]<br />
[[Category:Help and Docs]]<br />
[[Category:CHM]]</div>Mario13https://wiki.freepascal.org/index.php?title=Event_order&diff=78859Event order2014-04-18T11:47:37Z<p>Mario13: /* Forms */</p>
<hr />
<div>== Overview ==<br />
Lazarus offers various events that you can use to enter your own procedures to handle things that happen in your application (e.g. a user clicks a button).<br />
<br />
There are rather a lot of possible events to cater for a lot of different scenarios. Somebody who does not know Lazarus or Delphi could well pick the wrong event.<br />
<br />
== Lazarus documentation ==<br />
The [[Lazarus_Tutorial#Event_Actions Lazarus tutorial]] has some information on what events do what.<br />
<br />
== Forms ==<br />
Typical event order for forms is:<br />
OnCreate => OnShow => OnActivate => OnPaint => OnResize => OnPaint => ... <br />
OnCloseQuery => OnClose => OnDeactivate => OnHide => OnDestroy<br />
<br />
=== Form.OnCreate ===<br />
This is the equivalent to the class constructor in forms. Use this to initialize form-level variables etc. The form is not yet shown at this time.<br />
<br />
=== Form.OnShow ===<br />
When the form is shown (e.g. when loading the form or setting its <code>.Visible</code> property to true), this event is fired - just before the form is visible. This allows you to modify the visual appearance of controls (e.g. disable certain controls) without flickering.<br />
<br />
=== Form.OnActivate ===<br />
Fired once after Form.OnCreate.<br />
<br />
=== Form.OnDestroy ===<br />
The equivalent to a class destructor in forms. Use this to clean up/free variables.<br />
<br />
== General controls ==<br />
These events apply to various controls. Please use the Object Inspector to check if it is available for the control you're currently using.<br />
<br />
=== OnEditingDone ===<br />
The OnEditingDone event for controls can act like the Validate event in other programming languages: it indicates the user is done changing the control and intends to keep that value. The program can now check the control content for correctness, show error messages, update database fields, etc.<br />
<br />
{{Note|As soon as you click outside the control (even on a control that cannot receive focus) OnEditingDone is triggered.<br><br />
(See TControl.MouseDown procedure, introduced in r11778).}}<br />
<br />
== Applicable Delphi information ==<br />
Because the implementation of events in Lazarus and Delphi is similar, a lot of Delphi-related documentation is applicable to Lazarus with minor modifications.<br />
<br />
[http://docwiki.embarcadero.com/RADStudio/en/Events Delphi documentation] is often handy. You can search for the actual control you want to know more about to get a list of its events.<br />
<br />
If you want to know about the order in which events fire on a form, [http://delphi.about.com/od/formsdialogs/a/delphiformlife.htm this article from about.com] can be useful.<br />
<br />
== See also ==<br />
* [[Lazarus_Tutorial#Event_Actions Lazarus tutorial]]<br />
* [[Drop files event]]<br />
* [http://delphi.about.com/od/formsdialogs/a/delphiformlife.htm Article about event order]<br />
* [http://docwiki.embarcadero.com/RADStudio/en/Events Delphi documentation]<br />
<br />
[[Category:Lazarus]]<br />
[[Category:LCL]]<br />
[[Category: Event-driven programming]]</div>Mario13https://wiki.freepascal.org/index.php?title=Lazarus_Database_Overview&diff=66017Lazarus Database Overview2013-02-18T21:01:34Z<p>Mario13: /* Lazarus and Paradox */</p>
<hr />
<div>{{Translate}}<br />
<br />
== Overview ==<br />
<br />
This article is an overview of the which databases can work with Lazarus.<br />
<br />
Lazarus supports several databases out of the box (using e.g. the SQLDB framework), however the developer must install the required packages (client libraries) for each one. <br />
<br />
You can access the database through code or by dropping components on a form. The data-aware components represent fields and are connected by setting the DataSource property to point to a TDataSource. The Datasource represents a table and is connected to the database components (examples: ''TPSQLDatabase'', ''TSQLiteDataSet'') by setting the DataSet property. The data-aware components are located on the "Data Controls" tab. The Datasource and the database controls are located on the "Data Access" tab.<br />
<br />
== Lazarus and Interbase / Firebird ==<br />
* Please see [[Firebird_in_action|Firebird in action]] for details on various access methods, which include<br />
# Built-in SQLDB support<br />
# FBLib<br />
# IBX<br />
# PDO<br />
# Zeos<br />
<br />
For a tutorial that leads you through creating a Lazarus GUI for a Firebird database, see:<br />
* [[SQLdb Tutorial1]]<br />
<br />
<br />
== Lazarus and MySQL ==<br />
* Please see [[mysql]] for details on various access methods, which include:<br />
# Built-in SQLDB support<br />
# PDO<br />
# Zeos<br />
<br />
== Lazarus and MSSQL/Sybase ==<br />
You can connect to Microsoft SQL Server databases using<br />
# The built-in '''SQLdb''' (recent Lazarus/FPC 2.6.1+): '''TMSSQLConnection''' (MS SQL) and '''TSybaseConnection''' (Sybase ASE)<br />
## On Windows, you can download a recent 32 or 64 bit version of the FreeTDS library '''dblib.dll''' here: [ftp://ftp.freepascal.org/fpc/contrib/windows/]<br />
## Not necessary normally: By modifying FPC file '''dblib.pas''' SQLDB could use the "native" library '''ntwdblib.dll''' instead of the default FreeTDS library '''dblib.dll''' (in this case FPC needs to be recompiled).<br />
## On Linux by default it uses the FreeTDS library '''libsybdb.so''' (for example, in Debian is in package '''libsybd5''').<br />
# '''Zeos''' component '''TZConnection''' (latest CVS, see links to Zeos elsewhere on this page)<br />
## On Windows you can choose between native library '''ntwdblib.dll''' (protocol '''mssql''') or FreeTDS libraries (protocol '''FreeTDS_MsSQL-nnnn''') where nnnn is one of four variants depending on the server version. For Delphi (not Lazarus) there is also another Zeos protocol '''ado''' for MSSQL 2005 or later. Using protocols mssql or ado generates code not platform independient.<br />
## On Linux the only way is with FreeTDS protocols and libraries (you should use '''libsybdb.so''').<br />
# '''ODBC''' (MSSQL and Sybase ASE) with SQLdb '''TODBCConnection''' (see also [http://wiki.freepascal.org/ODBCConn#Connecting_to_Microsoft_SQL_Server])<br />
## On Windows it uses native ODBC Microsoft libraries (like sqlsrv32.dll for MSSQL 2000)<br />
## On Linux it uses unixODBC + FreeTDS (packages unixodbc or iodbc, and tdsodbc). Since 2012 there is also a Microsoft SQL Server ODBC Driver 1.0 for Linux which is a binary product (no open source) and provides native connectivity, but was released only for 64 bits and only for RedHat.<br />
<br />
Please see the FPC and Lazarus help files for details on using SQLDB with Sybase ASE and MSSQL Server.<br />
<br />
{{Note| In any of the above forms, you can connect using TCP/IP, e.g. on port 1433. }}<br />
<br />
If you use native Microsoft Libraries (over Windows) it could be possible to connect to remote server with Named Pipes. FreeTDS libraries do not support Named Pipes.<br />
<br />
{{Note| Lazarus 1.0 was released with FPC 2.6.0 and does not include TMSSQLConnection or TSybaseConnection. If you want these, it might be easiest to download a snapshot of the latest Lazarus built with FPC 2.6.1, optinally installing that in a directory different from your Lazarus 1.0 version. You can use --primary-config-path to set up a separate environment for the Lazarus snapshot (see [[Multiple Lazarus]]) }}<br />
<br />
== Lazarus and ODBC ==<br />
ODBC is a general database connection standard which is available on Linux, Windows and OSX. You will need an ODBC driver from your database vendor and set up an ODBC "data source" (also known as DSN).<br />
You can use the SQLDB components (TODBCConnection) to connect to an ODBC data soruce.<br />
See [[ODBCConn]] for more details and examples<br />
<br />
== Lazarus and Oracle ==<br />
* Acces methods include:<br />
# Built-in SQLDB support<br />
# Zeos<br />
<br />
== Lazarus and PostgreSQL ==<br />
* Please see [[postgres]] for details on various access methods, which include:<br />
# Built-in SQLdb support. Use component '''TPQConnection''' from palette '''SQLdb'''<br />
# Zeos. Use component '''TZConnection''' with protocol 'postgresql' from palette '''Zeos Access'''<br />
<br />
== Lazarus and SQLite ==<br />
SQLite is an embedded database; the database code can be distributed as a library (.dll/.so/.dylib) with your application to make it self-contained (comparable to Firebird embedded). SQLite is quite popular due to its relative simplicity, speed, small size and cross-platform support.<br />
<br />
Please see the [[SQLite]] page for details on various access methods, which include:<br />
# Built-in SQLDb support<br />
# Zeos<br />
# SQLitePass <br />
# TSQLite3Dataset<br />
<br />
== Lazarus and dBase ==<br />
<br />
FPC includes a simple database component that is derived from the Delphi TTable component called "TDbf" [http://tdbf.sourceforge.net/ TDbf Website]). It supports various DBase and Foxpro formats.<br />
<br />
TDbf does not accept SQL commands but you can use the dataset methods etc and you can also use regular databound controls such as the DBGrid.<br />
<br />
It doesn't require any sort of runtime database engine. However it's not the best option for large database applications.<br />
<br />
See the [[Lazarus Tdbf Tutorial|TDbf Tutorial page]] for the tutorial as well as documentation.<br />
<br />
You can use e.g. OpenOffice/LibreOffice Base to visually create/edit dbf files.<br />
<br />
When this code is run, your DVD collection table will be created. After that, all data aware components linked through the TDatasource to this component will allow easy access to the data.<br />
<br />
<br />
== Lazarus and Paradox ==<br />
<br />
Paradox was the default format for database files in Delphi and before (view [http://en.wikipedia.org/wiki/Paradox_%28database%29 Wikipedia]).<br />
The concept is similar to DBF's, where the "database" is a folder, and each table is a "file" inside that folder. Also, each index is a file too.<br />
To access this files from Lazarus we have these options:<br />
<br />
* '''TParadox''': Install package "lazparadox 0.0" included in the standard distribution. When you install this package, you will see a new component labeled "PDX" in the "Data Access" palette. This component is not standalone, it uses a "native" library, namely the [http://pxlib.sourceforge.net pdxlib library] which is available for Linux. For example, to install in Debian, you could get '''pxlib1''' from package manager. In Windows you need pxlib.dll file. <br />
<br />
* '''TPdx''': Paradox DataSet for Lazarus and Delphi from [http://tpdx.sourceforge.net/ this site]. This component is standalone (pure object pascal), not requiring any external library, but it can only read (not write) Paradox files. The package to install is "paradoxlaz.lpk" and the component should appear in the "Data Access" palette with PDX label (but orange colour). <br />
<br />
* '''TParadoxDataSet''': is a TDataSet that can only read Paradox Files up to Version 7. See this [http://wiki.lazarus.freepascal.org/TParadoxDataSet wiki page]. The approach is similar to the TPdx component, the package to install is "lazparadox.lpk" and the component should also appear in the "Data Access" palette.<br />
<br />
== Using TSdfDataset and TFixedDataset ==<br />
<br />
TSdfDataset and TFixedDataset are two simple datasets which offer a very simple textual storage format. These datasets are very convenient for small databases, because they are fully implemented as an object pascal unit, and thus require no external libraries, and because their textual format allows them to be easely edited with a text editor.<br />
<br />
Note: December 2012/FPC 2.7.1: SDFDataset is supposed to read/write CSV files according to RFC4180, but still has some problems with quoted fields etc. For more details, see [[CSV]]<br />
<br />
To start with this format, a initial database file should be created. The format is very simple, so use a text editor to do this.<br />
<br />
Bellow is a sample database for TSdfDataset. Note that the first line has the names of the fields and that we are using commas as separators:<br />
<br />
<pre>ID,NAMEEN,NAMEPT,HEIGHT,WIDTH,PINS,DRAWINGCODE<br />
1,resistor,resistor,1,1,1,LINE<br />
2,capacitor,capacitor,1,1,1,LINE<br />
3,transistor npn,transistor npn</pre><br />
<br />
And here is an example database for using with TFixedDataset. Each record occupies a fixed amount of space, and if the field is smaller then it, spaces should be used to fill the remaining size.<br />
<br />
<pre>Name = 15 chars; Surname = 15 chars; Tell = 10 chars; e_mail = 20 chars;<br />
Piet Pompies piet@pompies.net</pre><br />
<br />
=== Using the datasets directly ===<br />
<br />
Sometimes it is useful to create the dataset and work with it completely in code, and the following code will do exactly this. Note some peculiarities of TSdfDataset/TFixedDataset:<br />
<br />
* The lines in the database can have a maximum size of about 300. A fix is being researched.<br />
* It is necessary to add the field definitions. Some datasets are able to fill this information alone from the database file<br />
* One should set FirstLineAsSchema to true, to indicate that the first line includes the field names and positions<br />
* The Delimiter property holds the separator for the fields. It will not be possible to use this char in strings in the database. Similarly it will not be possible to have lineendings in the database because they mark the change between records. It's possible to overcome this by substituting the needed comma or line ending with another not often used char, like # for example. So that when showing the data on screen all # chars could be converted to line endings and the inverse when storing data back to the database. The ReplaceString routine is useful here.<br />
<br />
<syntaxhighlight><br />
uses sdfdata, db;<br />
<br />
constructor TComponentsDatabase.Create;<br />
var<br />
FDataset: TSdfDataset;<br />
begin<br />
inherited Create;<br />
<br />
FDataset := TSdfDataset.Create(nil);<br />
FDataset.FileName := vConfigurations.ComponentsDBFile;<br />
<br />
// Not necessary with TSdfDataset<br />
// FDataset.TableName := STR_DB_COMPONENTS_TABLE;<br />
// FDataset.PrimaryKey := STR_DB_COMPONENTS_ID;<br />
<br />
// Adds field definitions<br />
FDataset.FieldDefs.Add('ID', ftString);<br />
FDataset.FieldDefs.Add('NAMEEN', ftString);<br />
FDataset.FieldDefs.Add('NAMEPT', ftString);<br />
FDataset.FieldDefs.Add('HEIGHT', ftString);<br />
FDataset.FieldDefs.Add('WIDTH', ftString);<br />
FDataset.FieldDefs.Add('PINS', ftString);<br />
FDataset.FieldDefs.Add('DRAWINGCODE', ftString);<br />
<br />
// Necessary for TSdfDataset<br />
FDataset.Delimiter := ',';<br />
FDataset.FirstLineAsSchema := True;<br />
<br />
FDataset.Active := True;<br />
<br />
// Sets the initial record<br />
CurrentRecNo := 1;<br />
FDataset.First;<br />
end;</syntaxhighlight><br />
<br />
When using TSdfDataset directly be aware that RecNo, although it is implemented, does not work as a way to move through the dataset whether reading or writing records. The standard navigation routines like First, Next, Prior and Last work as expected, so you need to use them rather than RecNo.<br />
If you are used to using absolute record numbers to navigate around a database you can implement your own version of RecNo. Declare a global longint variable called CurrentRecNo which will hold the current RecNo value. Remember that this variable will have the same convention as RecNo, so the first record has number 1 (it is not zero-based). After activating the database initialize the database to the first record with TSdfDataset.First and set CurrentRecNo := 1<br />
<br />
<syntaxhighlight>{@@<br />
Moves to the desired record using TDataset.Next and TDataset.Prior<br />
This avoids using TDataset.RecNo which doesn't navigate reliably in any dataset.<br />
<br />
@param AID Indicates the record number. The first record has number 1<br />
}<br />
procedure TComponentsDatabase.GoToRec(AID: Integer);<br />
begin<br />
// We are before the desired record, move forward<br />
if CurrentRecNo < AID then<br />
begin<br />
while (not FDataset.EOF) and (CurrentRecNo < AID) do<br />
begin<br />
FDataset.Next;<br />
FDataset.CursorPosChanged;<br />
Inc(CurrentRecNo);<br />
end;<br />
end<br />
// We are after the desired record, move back<br />
else if CurrentRecNo > AID then<br />
begin<br />
while (CurrentRecNo >= 1) and (CurrentRecNo > AID) do<br />
begin<br />
FDataset.Prior;<br />
FDataset.CursorPosChanged;<br />
Dec(CurrentRecNo);<br />
end;<br />
end;<br />
end;</syntaxhighlight><br />
<br />
=== Using with data-aware controls ===<br />
<br />
== Lazarus and Advantage Database Server ==<br />
* Please see [[Advantage Database Server]] for details on using Advantage Database Server<br />
<br />
==See also==<br />
(Sorted alphabetically)<br />
* [[Databases]]<br />
* [[Database_field_type]]<br />
* [[Firebird in action]]<br />
* [[How to write in-memory database applications in Lazarus/FPC]]<br />
* [[Lazarus DB Faq]]<br />
* [[Lazarus Tdbf Tutorial]]<br />
* [[MS Access]]<br />
* [[multi-tier_options_with_fpc|Multi-tier options with FPC]]<br />
* [[MySQLDatabases]]<br />
* [[ODBCConn]]<br />
* [[SQLdb Tutorial1]]<br />
* [[SqlDBHowto]]<br />
* [[SQLite]]<br />
* [[tiOPF]] - a free and open source Object Persistence Framework.<br />
* [[Zeos tutorial]]<br />
<br />
==External links==<br />
<br />
* [http://pdo.sourceforge.net Pascal Data Objects] - a database API that worked for both FPC and Delphi and utilises native MySQL libraries for version 4.1 and 5.0 and Firebird SQL 1.5, and 2.0. It's inspired by PHP's PDO class.<br />
* [http://lazaruszeos.blogspot.com Zeos+SQLite Tutorial] - Good tutorial using screenshots and screencasts it explain how to use SQLite and Zeos, spanish (google translate does a good work in translating it to english)<br />
<br />
<br />
[[Category:Databases]]<br />
[[Category:Tutorials]]</div>Mario13https://wiki.freepascal.org/index.php?title=Lazarus_Database_Overview&diff=66016Lazarus Database Overview2013-02-18T20:04:37Z<p>Mario13: /* Lazarus and Paradox */</p>
<hr />
<div>{{Translate}}<br />
<br />
== Overview ==<br />
<br />
This article is an overview of the which databases can work with Lazarus.<br />
<br />
Lazarus supports several databases out of the box (using e.g. the SQLDB framework), however the developer must install the required packages (client libraries) for each one. <br />
<br />
You can access the database through code or by dropping components on a form. The data-aware components represent fields and are connected by setting the DataSource property to point to a TDataSource. The Datasource represents a table and is connected to the database components (examples: ''TPSQLDatabase'', ''TSQLiteDataSet'') by setting the DataSet property. The data-aware components are located on the "Data Controls" tab. The Datasource and the database controls are located on the "Data Access" tab.<br />
<br />
== Lazarus and Interbase / Firebird ==<br />
* Please see [[Firebird_in_action|Firebird in action]] for details on various access methods, which include<br />
# Built-in SQLDB support<br />
# FBLib<br />
# IBX<br />
# PDO<br />
# Zeos<br />
<br />
For a tutorial that leads you through creating a Lazarus GUI for a Firebird database, see:<br />
* [[SQLdb Tutorial1]]<br />
<br />
<br />
== Lazarus and MySQL ==<br />
* Please see [[mysql]] for details on various access methods, which include:<br />
# Built-in SQLDB support<br />
# PDO<br />
# Zeos<br />
<br />
== Lazarus and MSSQL/Sybase ==<br />
You can connect to Microsoft SQL Server databases using<br />
# The built-in '''SQLdb''' (recent Lazarus/FPC 2.6.1+): '''TMSSQLConnection''' (MS SQL) and '''TSybaseConnection''' (Sybase ASE)<br />
## On Windows, you can download a recent 32 or 64 bit version of the FreeTDS library '''dblib.dll''' here: [ftp://ftp.freepascal.org/fpc/contrib/windows/]<br />
## Not necessary normally: By modifying FPC file '''dblib.pas''' SQLDB could use the "native" library '''ntwdblib.dll''' instead of the default FreeTDS library '''dblib.dll''' (in this case FPC needs to be recompiled).<br />
## On Linux by default it uses the FreeTDS library '''libsybdb.so''' (for example, in Debian is in package '''libsybd5''').<br />
# '''Zeos''' component '''TZConnection''' (latest CVS, see links to Zeos elsewhere on this page)<br />
## On Windows you can choose between native library '''ntwdblib.dll''' (protocol '''mssql''') or FreeTDS libraries (protocol '''FreeTDS_MsSQL-nnnn''') where nnnn is one of four variants depending on the server version. For Delphi (not Lazarus) there is also another Zeos protocol '''ado''' for MSSQL 2005 or later. Using protocols mssql or ado generates code not platform independient.<br />
## On Linux the only way is with FreeTDS protocols and libraries (you should use '''libsybdb.so''').<br />
# '''ODBC''' (MSSQL and Sybase ASE) with SQLdb '''TODBCConnection''' (see also [http://wiki.freepascal.org/ODBCConn#Connecting_to_Microsoft_SQL_Server])<br />
## On Windows it uses native ODBC Microsoft libraries (like sqlsrv32.dll for MSSQL 2000)<br />
## On Linux it uses unixODBC + FreeTDS (packages unixodbc or iodbc, and tdsodbc). Since 2012 there is also a Microsoft SQL Server ODBC Driver 1.0 for Linux which is a binary product (no open source) and provides native connectivity, but was released only for 64 bits and only for RedHat.<br />
<br />
Please see the FPC and Lazarus help files for details on using SQLDB with Sybase ASE and MSSQL Server.<br />
<br />
{{Note| In any of the above forms, you can connect using TCP/IP, e.g. on port 1433. }}<br />
<br />
If you use native Microsoft Libraries (over Windows) it could be possible to connect to remote server with Named Pipes. FreeTDS libraries do not support Named Pipes.<br />
<br />
{{Note| Lazarus 1.0 was released with FPC 2.6.0 and does not include TMSSQLConnection or TSybaseConnection. If you want these, it might be easiest to download a snapshot of the latest Lazarus built with FPC 2.6.1, optinally installing that in a directory different from your Lazarus 1.0 version. You can use --primary-config-path to set up a separate environment for the Lazarus snapshot (see [[Multiple Lazarus]]) }}<br />
<br />
== Lazarus and ODBC ==<br />
ODBC is a general database connection standard which is available on Linux, Windows and OSX. You will need an ODBC driver from your database vendor and set up an ODBC "data source" (also known as DSN).<br />
You can use the SQLDB components (TODBCConnection) to connect to an ODBC data soruce.<br />
See [[ODBCConn]] for more details and examples<br />
<br />
== Lazarus and Oracle ==<br />
* Acces methods include:<br />
# Built-in SQLDB support<br />
# Zeos<br />
<br />
== Lazarus and PostgreSQL ==<br />
* Please see [[postgres]] for details on various access methods, which include:<br />
# Built-in SQLdb support. Use component '''TPQConnection''' from palette '''SQLdb'''<br />
# Zeos. Use component '''TZConnection''' with protocol 'postgresql' from palette '''Zeos Access'''<br />
<br />
== Lazarus and SQLite ==<br />
SQLite is an embedded database; the database code can be distributed as a library (.dll/.so/.dylib) with your application to make it self-contained (comparable to Firebird embedded). SQLite is quite popular due to its relative simplicity, speed, small size and cross-platform support.<br />
<br />
Please see the [[SQLite]] page for details on various access methods, which include:<br />
# Built-in SQLDb support<br />
# Zeos<br />
# SQLitePass <br />
# TSQLite3Dataset<br />
<br />
== Lazarus and dBase ==<br />
<br />
FPC includes a simple database component that is derived from the Delphi TTable component called "TDbf" [http://tdbf.sourceforge.net/ TDbf Website]). It supports various DBase and Foxpro formats.<br />
<br />
TDbf does not accept SQL commands but you can use the dataset methods etc and you can also use regular databound controls such as the DBGrid.<br />
<br />
It doesn't require any sort of runtime database engine. However it's not the best option for large database applications.<br />
<br />
See the [[Lazarus Tdbf Tutorial|TDbf Tutorial page]] for the tutorial as well as documentation.<br />
<br />
You can use e.g. OpenOffice/LibreOffice Base to visually create/edit dbf files.<br />
<br />
When this code is run, your DVD collection table will be created. After that, all data aware components linked through the TDatasource to this component will allow easy access to the data.<br />
<br />
<br />
== Lazarus and Paradox ==<br />
<br />
Paradox was the default format for table files in Delphi and before (view [http://en.wikipedia.org/wiki/Paradox_%28database%29 Wikipedia]).<br />
The concept is similar to DBF's, where the "database" is a folder, and each table is a "file" inside that folder. Also, each index is a file too.<br />
To access this files from Lazarus we have these options:<br />
<br />
* '''TParadox''': Install package "lazparadox 0.0" included in the standard distribution. When you install this package, you will see a new component labeled "PDX" in the "Data Access" palette. In order to use this component you have to include "paradox" in the uses list. This component is not standalone, it uses a "native" library, namely the [http://pxlib.sourceforge.net pdxlib library] which is available for Linux. Alternatively for example in Debian, you could install '''pxlib1''' from package manager.<br />
<br />
* '''TPdx''': Paradox DataSet for Lazarus and Delphi from [http://tpdx.sourceforge.net/ this site]. This component is standalone (pure object pascal), not requiring any external library. The package to install is "paradoxlaz.lpk" and the component should appear in the "Data Access" palette. <br />
<br />
* '''TParadoxDataSet''': is a TDataSet that can only read Paradox Files up to Version 7. See this [http://wiki.lazarus.freepascal.org/TParadoxDataSet wiki page]. The approach is similar to the TPdx component, the package to install is "lazparadox.lpk" and the component should also appear in the "Data Access" palette.<br />
<br />
== Using TSdfDataset and TFixedDataset ==<br />
<br />
TSdfDataset and TFixedDataset are two simple datasets which offer a very simple textual storage format. These datasets are very convenient for small databases, because they are fully implemented as an object pascal unit, and thus require no external libraries, and because their textual format allows them to be easely edited with a text editor.<br />
<br />
Note: December 2012/FPC 2.7.1: SDFDataset is supposed to read/write CSV files according to RFC4180, but still has some problems with quoted fields etc. For more details, see [[CSV]]<br />
<br />
To start with this format, a initial database file should be created. The format is very simple, so use a text editor to do this.<br />
<br />
Bellow is a sample database for TSdfDataset. Note that the first line has the names of the fields and that we are using commas as separators:<br />
<br />
<pre>ID,NAMEEN,NAMEPT,HEIGHT,WIDTH,PINS,DRAWINGCODE<br />
1,resistor,resistor,1,1,1,LINE<br />
2,capacitor,capacitor,1,1,1,LINE<br />
3,transistor npn,transistor npn</pre><br />
<br />
And here is an example database for using with TFixedDataset. Each record occupies a fixed amount of space, and if the field is smaller then it, spaces should be used to fill the remaining size.<br />
<br />
<pre>Name = 15 chars; Surname = 15 chars; Tell = 10 chars; e_mail = 20 chars;<br />
Piet Pompies piet@pompies.net</pre><br />
<br />
=== Using the datasets directly ===<br />
<br />
Sometimes it is useful to create the dataset and work with it completely in code, and the following code will do exactly this. Note some peculiarities of TSdfDataset/TFixedDataset:<br />
<br />
* The lines in the database can have a maximum size of about 300. A fix is being researched.<br />
* It is necessary to add the field definitions. Some datasets are able to fill this information alone from the database file<br />
* One should set FirstLineAsSchema to true, to indicate that the first line includes the field names and positions<br />
* The Delimiter property holds the separator for the fields. It will not be possible to use this char in strings in the database. Similarly it will not be possible to have lineendings in the database because they mark the change between records. It's possible to overcome this by substituting the needed comma or line ending with another not often used char, like # for example. So that when showing the data on screen all # chars could be converted to line endings and the inverse when storing data back to the database. The ReplaceString routine is useful here.<br />
<br />
<syntaxhighlight><br />
uses sdfdata, db;<br />
<br />
constructor TComponentsDatabase.Create;<br />
var<br />
FDataset: TSdfDataset;<br />
begin<br />
inherited Create;<br />
<br />
FDataset := TSdfDataset.Create(nil);<br />
FDataset.FileName := vConfigurations.ComponentsDBFile;<br />
<br />
// Not necessary with TSdfDataset<br />
// FDataset.TableName := STR_DB_COMPONENTS_TABLE;<br />
// FDataset.PrimaryKey := STR_DB_COMPONENTS_ID;<br />
<br />
// Adds field definitions<br />
FDataset.FieldDefs.Add('ID', ftString);<br />
FDataset.FieldDefs.Add('NAMEEN', ftString);<br />
FDataset.FieldDefs.Add('NAMEPT', ftString);<br />
FDataset.FieldDefs.Add('HEIGHT', ftString);<br />
FDataset.FieldDefs.Add('WIDTH', ftString);<br />
FDataset.FieldDefs.Add('PINS', ftString);<br />
FDataset.FieldDefs.Add('DRAWINGCODE', ftString);<br />
<br />
// Necessary for TSdfDataset<br />
FDataset.Delimiter := ',';<br />
FDataset.FirstLineAsSchema := True;<br />
<br />
FDataset.Active := True;<br />
<br />
// Sets the initial record<br />
CurrentRecNo := 1;<br />
FDataset.First;<br />
end;</syntaxhighlight><br />
<br />
When using TSdfDataset directly be aware that RecNo, although it is implemented, does not work as a way to move through the dataset whether reading or writing records. The standard navigation routines like First, Next, Prior and Last work as expected, so you need to use them rather than RecNo.<br />
If you are used to using absolute record numbers to navigate around a database you can implement your own version of RecNo. Declare a global longint variable called CurrentRecNo which will hold the current RecNo value. Remember that this variable will have the same convention as RecNo, so the first record has number 1 (it is not zero-based). After activating the database initialize the database to the first record with TSdfDataset.First and set CurrentRecNo := 1<br />
<br />
<syntaxhighlight>{@@<br />
Moves to the desired record using TDataset.Next and TDataset.Prior<br />
This avoids using TDataset.RecNo which doesn't navigate reliably in any dataset.<br />
<br />
@param AID Indicates the record number. The first record has number 1<br />
}<br />
procedure TComponentsDatabase.GoToRec(AID: Integer);<br />
begin<br />
// We are before the desired record, move forward<br />
if CurrentRecNo < AID then<br />
begin<br />
while (not FDataset.EOF) and (CurrentRecNo < AID) do<br />
begin<br />
FDataset.Next;<br />
FDataset.CursorPosChanged;<br />
Inc(CurrentRecNo);<br />
end;<br />
end<br />
// We are after the desired record, move back<br />
else if CurrentRecNo > AID then<br />
begin<br />
while (CurrentRecNo >= 1) and (CurrentRecNo > AID) do<br />
begin<br />
FDataset.Prior;<br />
FDataset.CursorPosChanged;<br />
Dec(CurrentRecNo);<br />
end;<br />
end;<br />
end;</syntaxhighlight><br />
<br />
=== Using with data-aware controls ===<br />
<br />
== Lazarus and Advantage Database Server ==<br />
* Please see [[Advantage Database Server]] for details on using Advantage Database Server<br />
<br />
==See also==<br />
(Sorted alphabetically)<br />
* [[Databases]]<br />
* [[Database_field_type]]<br />
* [[Firebird in action]]<br />
* [[How to write in-memory database applications in Lazarus/FPC]]<br />
* [[Lazarus DB Faq]]<br />
* [[Lazarus Tdbf Tutorial]]<br />
* [[MS Access]]<br />
* [[multi-tier_options_with_fpc|Multi-tier options with FPC]]<br />
* [[MySQLDatabases]]<br />
* [[ODBCConn]]<br />
* [[SQLdb Tutorial1]]<br />
* [[SqlDBHowto]]<br />
* [[SQLite]]<br />
* [[tiOPF]] - a free and open source Object Persistence Framework.<br />
* [[Zeos tutorial]]<br />
<br />
==External links==<br />
<br />
* [http://pdo.sourceforge.net Pascal Data Objects] - a database API that worked for both FPC and Delphi and utilises native MySQL libraries for version 4.1 and 5.0 and Firebird SQL 1.5, and 2.0. It's inspired by PHP's PDO class.<br />
* [http://lazaruszeos.blogspot.com Zeos+SQLite Tutorial] - Good tutorial using screenshots and screencasts it explain how to use SQLite and Zeos, spanish (google translate does a good work in translating it to english)<br />
<br />
<br />
[[Category:Databases]]<br />
[[Category:Tutorials]]</div>Mario13https://wiki.freepascal.org/index.php?title=Lazarus_Database_Overview&diff=66015Lazarus Database Overview2013-02-18T20:03:40Z<p>Mario13: /* Lazarus and Paradox */</p>
<hr />
<div>{{Translate}}<br />
<br />
== Overview ==<br />
<br />
This article is an overview of the which databases can work with Lazarus.<br />
<br />
Lazarus supports several databases out of the box (using e.g. the SQLDB framework), however the developer must install the required packages (client libraries) for each one. <br />
<br />
You can access the database through code or by dropping components on a form. The data-aware components represent fields and are connected by setting the DataSource property to point to a TDataSource. The Datasource represents a table and is connected to the database components (examples: ''TPSQLDatabase'', ''TSQLiteDataSet'') by setting the DataSet property. The data-aware components are located on the "Data Controls" tab. The Datasource and the database controls are located on the "Data Access" tab.<br />
<br />
== Lazarus and Interbase / Firebird ==<br />
* Please see [[Firebird_in_action|Firebird in action]] for details on various access methods, which include<br />
# Built-in SQLDB support<br />
# FBLib<br />
# IBX<br />
# PDO<br />
# Zeos<br />
<br />
For a tutorial that leads you through creating a Lazarus GUI for a Firebird database, see:<br />
* [[SQLdb Tutorial1]]<br />
<br />
<br />
== Lazarus and MySQL ==<br />
* Please see [[mysql]] for details on various access methods, which include:<br />
# Built-in SQLDB support<br />
# PDO<br />
# Zeos<br />
<br />
== Lazarus and MSSQL/Sybase ==<br />
You can connect to Microsoft SQL Server databases using<br />
# The built-in '''SQLdb''' (recent Lazarus/FPC 2.6.1+): '''TMSSQLConnection''' (MS SQL) and '''TSybaseConnection''' (Sybase ASE)<br />
## On Windows, you can download a recent 32 or 64 bit version of the FreeTDS library '''dblib.dll''' here: [ftp://ftp.freepascal.org/fpc/contrib/windows/]<br />
## Not necessary normally: By modifying FPC file '''dblib.pas''' SQLDB could use the "native" library '''ntwdblib.dll''' instead of the default FreeTDS library '''dblib.dll''' (in this case FPC needs to be recompiled).<br />
## On Linux by default it uses the FreeTDS library '''libsybdb.so''' (for example, in Debian is in package '''libsybd5''').<br />
# '''Zeos''' component '''TZConnection''' (latest CVS, see links to Zeos elsewhere on this page)<br />
## On Windows you can choose between native library '''ntwdblib.dll''' (protocol '''mssql''') or FreeTDS libraries (protocol '''FreeTDS_MsSQL-nnnn''') where nnnn is one of four variants depending on the server version. For Delphi (not Lazarus) there is also another Zeos protocol '''ado''' for MSSQL 2005 or later. Using protocols mssql or ado generates code not platform independient.<br />
## On Linux the only way is with FreeTDS protocols and libraries (you should use '''libsybdb.so''').<br />
# '''ODBC''' (MSSQL and Sybase ASE) with SQLdb '''TODBCConnection''' (see also [http://wiki.freepascal.org/ODBCConn#Connecting_to_Microsoft_SQL_Server])<br />
## On Windows it uses native ODBC Microsoft libraries (like sqlsrv32.dll for MSSQL 2000)<br />
## On Linux it uses unixODBC + FreeTDS (packages unixodbc or iodbc, and tdsodbc). Since 2012 there is also a Microsoft SQL Server ODBC Driver 1.0 for Linux which is a binary product (no open source) and provides native connectivity, but was released only for 64 bits and only for RedHat.<br />
<br />
Please see the FPC and Lazarus help files for details on using SQLDB with Sybase ASE and MSSQL Server.<br />
<br />
{{Note| In any of the above forms, you can connect using TCP/IP, e.g. on port 1433. }}<br />
<br />
If you use native Microsoft Libraries (over Windows) it could be possible to connect to remote server with Named Pipes. FreeTDS libraries do not support Named Pipes.<br />
<br />
{{Note| Lazarus 1.0 was released with FPC 2.6.0 and does not include TMSSQLConnection or TSybaseConnection. If you want these, it might be easiest to download a snapshot of the latest Lazarus built with FPC 2.6.1, optinally installing that in a directory different from your Lazarus 1.0 version. You can use --primary-config-path to set up a separate environment for the Lazarus snapshot (see [[Multiple Lazarus]]) }}<br />
<br />
== Lazarus and ODBC ==<br />
ODBC is a general database connection standard which is available on Linux, Windows and OSX. You will need an ODBC driver from your database vendor and set up an ODBC "data source" (also known as DSN).<br />
You can use the SQLDB components (TODBCConnection) to connect to an ODBC data soruce.<br />
See [[ODBCConn]] for more details and examples<br />
<br />
== Lazarus and Oracle ==<br />
* Acces methods include:<br />
# Built-in SQLDB support<br />
# Zeos<br />
<br />
== Lazarus and PostgreSQL ==<br />
* Please see [[postgres]] for details on various access methods, which include:<br />
# Built-in SQLdb support. Use component '''TPQConnection''' from palette '''SQLdb'''<br />
# Zeos. Use component '''TZConnection''' with protocol 'postgresql' from palette '''Zeos Access'''<br />
<br />
== Lazarus and SQLite ==<br />
SQLite is an embedded database; the database code can be distributed as a library (.dll/.so/.dylib) with your application to make it self-contained (comparable to Firebird embedded). SQLite is quite popular due to its relative simplicity, speed, small size and cross-platform support.<br />
<br />
Please see the [[SQLite]] page for details on various access methods, which include:<br />
# Built-in SQLDb support<br />
# Zeos<br />
# SQLitePass <br />
# TSQLite3Dataset<br />
<br />
== Lazarus and dBase ==<br />
<br />
FPC includes a simple database component that is derived from the Delphi TTable component called "TDbf" [http://tdbf.sourceforge.net/ TDbf Website]). It supports various DBase and Foxpro formats.<br />
<br />
TDbf does not accept SQL commands but you can use the dataset methods etc and you can also use regular databound controls such as the DBGrid.<br />
<br />
It doesn't require any sort of runtime database engine. However it's not the best option for large database applications.<br />
<br />
See the [[Lazarus Tdbf Tutorial|TDbf Tutorial page]] for the tutorial as well as documentation.<br />
<br />
You can use e.g. OpenOffice/LibreOffice Base to visually create/edit dbf files.<br />
<br />
When this code is run, your DVD collection table will be created. After that, all data aware components linked through the TDatasource to this component will allow easy access to the data.<br />
<br />
<br />
== Lazarus and Paradox ==<br />
<br />
Paradox was the default format for table files in Delphi and before (view [http://en.wikipedia.org/wiki/Paradox_%28database%29 Wikipedia]).<br />
The concept is similar to DBF's, where the "database" is a folder, and each table is a "file" inside that folder. Also, each index is a file too.<br />
To access this files from Lazarus we have this options:<br />
<br />
* '''TParadox''': Install package "lazparadox 0.0" included in the standard distribution. When you install this package, you will see a new component labeled "PDX" in the "Data Access" palette. In order to use this component you have to include "paradox" in the uses list. This component is not standalone, it uses a "native" library, namely the [http://pxlib.sourceforge.net pdxlib library] which is available for Linux. Alternatively for example in Debian, you could install '''pxlib1''' from package manager.<br />
<br />
* '''TPdx''': Paradox DataSet for Lazarus and Delphi from [http://tpdx.sourceforge.net/ this site]. This component is standalone (pure object pascal), not requiring any external library. The package to install is "paradoxlaz.lpk" and the component should appear in the "Data Access" palette. <br />
<br />
* '''TParadoxDataSet''': is a TDataSet that can only read Paradox Files up to Version 7. See this [http://wiki.lazarus.freepascal.org/TParadoxDataSet wiki page]. The approach is similar to the TPdx component, the package to install is "lazparadox.lpk" and the component should also appear in the "Data Access" palette.<br />
<br />
== Using TSdfDataset and TFixedDataset ==<br />
<br />
TSdfDataset and TFixedDataset are two simple datasets which offer a very simple textual storage format. These datasets are very convenient for small databases, because they are fully implemented as an object pascal unit, and thus require no external libraries, and because their textual format allows them to be easely edited with a text editor.<br />
<br />
Note: December 2012/FPC 2.7.1: SDFDataset is supposed to read/write CSV files according to RFC4180, but still has some problems with quoted fields etc. For more details, see [[CSV]]<br />
<br />
To start with this format, a initial database file should be created. The format is very simple, so use a text editor to do this.<br />
<br />
Bellow is a sample database for TSdfDataset. Note that the first line has the names of the fields and that we are using commas as separators:<br />
<br />
<pre>ID,NAMEEN,NAMEPT,HEIGHT,WIDTH,PINS,DRAWINGCODE<br />
1,resistor,resistor,1,1,1,LINE<br />
2,capacitor,capacitor,1,1,1,LINE<br />
3,transistor npn,transistor npn</pre><br />
<br />
And here is an example database for using with TFixedDataset. Each record occupies a fixed amount of space, and if the field is smaller then it, spaces should be used to fill the remaining size.<br />
<br />
<pre>Name = 15 chars; Surname = 15 chars; Tell = 10 chars; e_mail = 20 chars;<br />
Piet Pompies piet@pompies.net</pre><br />
<br />
=== Using the datasets directly ===<br />
<br />
Sometimes it is useful to create the dataset and work with it completely in code, and the following code will do exactly this. Note some peculiarities of TSdfDataset/TFixedDataset:<br />
<br />
* The lines in the database can have a maximum size of about 300. A fix is being researched.<br />
* It is necessary to add the field definitions. Some datasets are able to fill this information alone from the database file<br />
* One should set FirstLineAsSchema to true, to indicate that the first line includes the field names and positions<br />
* The Delimiter property holds the separator for the fields. It will not be possible to use this char in strings in the database. Similarly it will not be possible to have lineendings in the database because they mark the change between records. It's possible to overcome this by substituting the needed comma or line ending with another not often used char, like # for example. So that when showing the data on screen all # chars could be converted to line endings and the inverse when storing data back to the database. The ReplaceString routine is useful here.<br />
<br />
<syntaxhighlight><br />
uses sdfdata, db;<br />
<br />
constructor TComponentsDatabase.Create;<br />
var<br />
FDataset: TSdfDataset;<br />
begin<br />
inherited Create;<br />
<br />
FDataset := TSdfDataset.Create(nil);<br />
FDataset.FileName := vConfigurations.ComponentsDBFile;<br />
<br />
// Not necessary with TSdfDataset<br />
// FDataset.TableName := STR_DB_COMPONENTS_TABLE;<br />
// FDataset.PrimaryKey := STR_DB_COMPONENTS_ID;<br />
<br />
// Adds field definitions<br />
FDataset.FieldDefs.Add('ID', ftString);<br />
FDataset.FieldDefs.Add('NAMEEN', ftString);<br />
FDataset.FieldDefs.Add('NAMEPT', ftString);<br />
FDataset.FieldDefs.Add('HEIGHT', ftString);<br />
FDataset.FieldDefs.Add('WIDTH', ftString);<br />
FDataset.FieldDefs.Add('PINS', ftString);<br />
FDataset.FieldDefs.Add('DRAWINGCODE', ftString);<br />
<br />
// Necessary for TSdfDataset<br />
FDataset.Delimiter := ',';<br />
FDataset.FirstLineAsSchema := True;<br />
<br />
FDataset.Active := True;<br />
<br />
// Sets the initial record<br />
CurrentRecNo := 1;<br />
FDataset.First;<br />
end;</syntaxhighlight><br />
<br />
When using TSdfDataset directly be aware that RecNo, although it is implemented, does not work as a way to move through the dataset whether reading or writing records. The standard navigation routines like First, Next, Prior and Last work as expected, so you need to use them rather than RecNo.<br />
If you are used to using absolute record numbers to navigate around a database you can implement your own version of RecNo. Declare a global longint variable called CurrentRecNo which will hold the current RecNo value. Remember that this variable will have the same convention as RecNo, so the first record has number 1 (it is not zero-based). After activating the database initialize the database to the first record with TSdfDataset.First and set CurrentRecNo := 1<br />
<br />
<syntaxhighlight>{@@<br />
Moves to the desired record using TDataset.Next and TDataset.Prior<br />
This avoids using TDataset.RecNo which doesn't navigate reliably in any dataset.<br />
<br />
@param AID Indicates the record number. The first record has number 1<br />
}<br />
procedure TComponentsDatabase.GoToRec(AID: Integer);<br />
begin<br />
// We are before the desired record, move forward<br />
if CurrentRecNo < AID then<br />
begin<br />
while (not FDataset.EOF) and (CurrentRecNo < AID) do<br />
begin<br />
FDataset.Next;<br />
FDataset.CursorPosChanged;<br />
Inc(CurrentRecNo);<br />
end;<br />
end<br />
// We are after the desired record, move back<br />
else if CurrentRecNo > AID then<br />
begin<br />
while (CurrentRecNo >= 1) and (CurrentRecNo > AID) do<br />
begin<br />
FDataset.Prior;<br />
FDataset.CursorPosChanged;<br />
Dec(CurrentRecNo);<br />
end;<br />
end;<br />
end;</syntaxhighlight><br />
<br />
=== Using with data-aware controls ===<br />
<br />
== Lazarus and Advantage Database Server ==<br />
* Please see [[Advantage Database Server]] for details on using Advantage Database Server<br />
<br />
==See also==<br />
(Sorted alphabetically)<br />
* [[Databases]]<br />
* [[Database_field_type]]<br />
* [[Firebird in action]]<br />
* [[How to write in-memory database applications in Lazarus/FPC]]<br />
* [[Lazarus DB Faq]]<br />
* [[Lazarus Tdbf Tutorial]]<br />
* [[MS Access]]<br />
* [[multi-tier_options_with_fpc|Multi-tier options with FPC]]<br />
* [[MySQLDatabases]]<br />
* [[ODBCConn]]<br />
* [[SQLdb Tutorial1]]<br />
* [[SqlDBHowto]]<br />
* [[SQLite]]<br />
* [[tiOPF]] - a free and open source Object Persistence Framework.<br />
* [[Zeos tutorial]]<br />
<br />
==External links==<br />
<br />
* [http://pdo.sourceforge.net Pascal Data Objects] - a database API that worked for both FPC and Delphi and utilises native MySQL libraries for version 4.1 and 5.0 and Firebird SQL 1.5, and 2.0. It's inspired by PHP's PDO class.<br />
* [http://lazaruszeos.blogspot.com Zeos+SQLite Tutorial] - Good tutorial using screenshots and screencasts it explain how to use SQLite and Zeos, spanish (google translate does a good work in translating it to english)<br />
<br />
<br />
[[Category:Databases]]<br />
[[Category:Tutorials]]</div>Mario13https://wiki.freepascal.org/index.php?title=Lazarus_Database_Overview&diff=66014Lazarus Database Overview2013-02-18T20:03:03Z<p>Mario13: /* Lazarus and Paradox */</p>
<hr />
<div>{{Translate}}<br />
<br />
== Overview ==<br />
<br />
This article is an overview of the which databases can work with Lazarus.<br />
<br />
Lazarus supports several databases out of the box (using e.g. the SQLDB framework), however the developer must install the required packages (client libraries) for each one. <br />
<br />
You can access the database through code or by dropping components on a form. The data-aware components represent fields and are connected by setting the DataSource property to point to a TDataSource. The Datasource represents a table and is connected to the database components (examples: ''TPSQLDatabase'', ''TSQLiteDataSet'') by setting the DataSet property. The data-aware components are located on the "Data Controls" tab. The Datasource and the database controls are located on the "Data Access" tab.<br />
<br />
== Lazarus and Interbase / Firebird ==<br />
* Please see [[Firebird_in_action|Firebird in action]] for details on various access methods, which include<br />
# Built-in SQLDB support<br />
# FBLib<br />
# IBX<br />
# PDO<br />
# Zeos<br />
<br />
For a tutorial that leads you through creating a Lazarus GUI for a Firebird database, see:<br />
* [[SQLdb Tutorial1]]<br />
<br />
<br />
== Lazarus and MySQL ==<br />
* Please see [[mysql]] for details on various access methods, which include:<br />
# Built-in SQLDB support<br />
# PDO<br />
# Zeos<br />
<br />
== Lazarus and MSSQL/Sybase ==<br />
You can connect to Microsoft SQL Server databases using<br />
# The built-in '''SQLdb''' (recent Lazarus/FPC 2.6.1+): '''TMSSQLConnection''' (MS SQL) and '''TSybaseConnection''' (Sybase ASE)<br />
## On Windows, you can download a recent 32 or 64 bit version of the FreeTDS library '''dblib.dll''' here: [ftp://ftp.freepascal.org/fpc/contrib/windows/]<br />
## Not necessary normally: By modifying FPC file '''dblib.pas''' SQLDB could use the "native" library '''ntwdblib.dll''' instead of the default FreeTDS library '''dblib.dll''' (in this case FPC needs to be recompiled).<br />
## On Linux by default it uses the FreeTDS library '''libsybdb.so''' (for example, in Debian is in package '''libsybd5''').<br />
# '''Zeos''' component '''TZConnection''' (latest CVS, see links to Zeos elsewhere on this page)<br />
## On Windows you can choose between native library '''ntwdblib.dll''' (protocol '''mssql''') or FreeTDS libraries (protocol '''FreeTDS_MsSQL-nnnn''') where nnnn is one of four variants depending on the server version. For Delphi (not Lazarus) there is also another Zeos protocol '''ado''' for MSSQL 2005 or later. Using protocols mssql or ado generates code not platform independient.<br />
## On Linux the only way is with FreeTDS protocols and libraries (you should use '''libsybdb.so''').<br />
# '''ODBC''' (MSSQL and Sybase ASE) with SQLdb '''TODBCConnection''' (see also [http://wiki.freepascal.org/ODBCConn#Connecting_to_Microsoft_SQL_Server])<br />
## On Windows it uses native ODBC Microsoft libraries (like sqlsrv32.dll for MSSQL 2000)<br />
## On Linux it uses unixODBC + FreeTDS (packages unixodbc or iodbc, and tdsodbc). Since 2012 there is also a Microsoft SQL Server ODBC Driver 1.0 for Linux which is a binary product (no open source) and provides native connectivity, but was released only for 64 bits and only for RedHat.<br />
<br />
Please see the FPC and Lazarus help files for details on using SQLDB with Sybase ASE and MSSQL Server.<br />
<br />
{{Note| In any of the above forms, you can connect using TCP/IP, e.g. on port 1433. }}<br />
<br />
If you use native Microsoft Libraries (over Windows) it could be possible to connect to remote server with Named Pipes. FreeTDS libraries do not support Named Pipes.<br />
<br />
{{Note| Lazarus 1.0 was released with FPC 2.6.0 and does not include TMSSQLConnection or TSybaseConnection. If you want these, it might be easiest to download a snapshot of the latest Lazarus built with FPC 2.6.1, optinally installing that in a directory different from your Lazarus 1.0 version. You can use --primary-config-path to set up a separate environment for the Lazarus snapshot (see [[Multiple Lazarus]]) }}<br />
<br />
== Lazarus and ODBC ==<br />
ODBC is a general database connection standard which is available on Linux, Windows and OSX. You will need an ODBC driver from your database vendor and set up an ODBC "data source" (also known as DSN).<br />
You can use the SQLDB components (TODBCConnection) to connect to an ODBC data soruce.<br />
See [[ODBCConn]] for more details and examples<br />
<br />
== Lazarus and Oracle ==<br />
* Acces methods include:<br />
# Built-in SQLDB support<br />
# Zeos<br />
<br />
== Lazarus and PostgreSQL ==<br />
* Please see [[postgres]] for details on various access methods, which include:<br />
# Built-in SQLdb support. Use component '''TPQConnection''' from palette '''SQLdb'''<br />
# Zeos. Use component '''TZConnection''' with protocol 'postgresql' from palette '''Zeos Access'''<br />
<br />
== Lazarus and SQLite ==<br />
SQLite is an embedded database; the database code can be distributed as a library (.dll/.so/.dylib) with your application to make it self-contained (comparable to Firebird embedded). SQLite is quite popular due to its relative simplicity, speed, small size and cross-platform support.<br />
<br />
Please see the [[SQLite]] page for details on various access methods, which include:<br />
# Built-in SQLDb support<br />
# Zeos<br />
# SQLitePass <br />
# TSQLite3Dataset<br />
<br />
== Lazarus and dBase ==<br />
<br />
FPC includes a simple database component that is derived from the Delphi TTable component called "TDbf" [http://tdbf.sourceforge.net/ TDbf Website]). It supports various DBase and Foxpro formats.<br />
<br />
TDbf does not accept SQL commands but you can use the dataset methods etc and you can also use regular databound controls such as the DBGrid.<br />
<br />
It doesn't require any sort of runtime database engine. However it's not the best option for large database applications.<br />
<br />
See the [[Lazarus Tdbf Tutorial|TDbf Tutorial page]] for the tutorial as well as documentation.<br />
<br />
You can use e.g. OpenOffice/LibreOffice Base to visually create/edit dbf files.<br />
<br />
When this code is run, your DVD collection table will be created. After that, all data aware components linked through the TDatasource to this component will allow easy access to the data.<br />
<br />
<br />
== Lazarus and Paradox ==<br />
<br />
Paradox was the default format for table files in Delphi and before (view [http://en.wikipedia.org/wiki/Paradox_%28database%29 Wikipedia]).<br />
The concept is similar to DBF's, where the "database" is a folder, and each table is a "file" inside that folder. Also, each index is a file too.<br />
To access this files from Lazarus we have this options:<br />
<br />
* '''TParadox''': Install package "lazparadox 0.0" included in the standard distribution. When you install this package, you will see a new component labeled "PDX" in the "Data Access" palette. In order to use this component you have to include "paradox" in the uses list. This component is not standalone, it uses a "native" library, namely the [http://pxlib.sourceforge.net pdxlib library] which is available for Linux. Alternatively for example in Debian, you could to install '''pxlib1''' from package manager.<br />
<br />
* '''TPdx''': Paradox DataSet for Lazarus and Delphi from [http://tpdx.sourceforge.net/ this site]. This component is standalone (pure object pascal), not requiring any external library. The package to install is "paradoxlaz.lpk" and the component should appear in the "Data Access" palette. <br />
<br />
* '''TParadoxDataSet''': is a TDataSet that can only read Paradox Files up to Version 7. See this [http://wiki.lazarus.freepascal.org/TParadoxDataSet wiki page]. The approach is similar to the TPdx component, the package to install is "lazparadox.lpk" and the component should also appear in the "Data Access" palette.<br />
<br />
== Using TSdfDataset and TFixedDataset ==<br />
<br />
TSdfDataset and TFixedDataset are two simple datasets which offer a very simple textual storage format. These datasets are very convenient for small databases, because they are fully implemented as an object pascal unit, and thus require no external libraries, and because their textual format allows them to be easely edited with a text editor.<br />
<br />
Note: December 2012/FPC 2.7.1: SDFDataset is supposed to read/write CSV files according to RFC4180, but still has some problems with quoted fields etc. For more details, see [[CSV]]<br />
<br />
To start with this format, a initial database file should be created. The format is very simple, so use a text editor to do this.<br />
<br />
Bellow is a sample database for TSdfDataset. Note that the first line has the names of the fields and that we are using commas as separators:<br />
<br />
<pre>ID,NAMEEN,NAMEPT,HEIGHT,WIDTH,PINS,DRAWINGCODE<br />
1,resistor,resistor,1,1,1,LINE<br />
2,capacitor,capacitor,1,1,1,LINE<br />
3,transistor npn,transistor npn</pre><br />
<br />
And here is an example database for using with TFixedDataset. Each record occupies a fixed amount of space, and if the field is smaller then it, spaces should be used to fill the remaining size.<br />
<br />
<pre>Name = 15 chars; Surname = 15 chars; Tell = 10 chars; e_mail = 20 chars;<br />
Piet Pompies piet@pompies.net</pre><br />
<br />
=== Using the datasets directly ===<br />
<br />
Sometimes it is useful to create the dataset and work with it completely in code, and the following code will do exactly this. Note some peculiarities of TSdfDataset/TFixedDataset:<br />
<br />
* The lines in the database can have a maximum size of about 300. A fix is being researched.<br />
* It is necessary to add the field definitions. Some datasets are able to fill this information alone from the database file<br />
* One should set FirstLineAsSchema to true, to indicate that the first line includes the field names and positions<br />
* The Delimiter property holds the separator for the fields. It will not be possible to use this char in strings in the database. Similarly it will not be possible to have lineendings in the database because they mark the change between records. It's possible to overcome this by substituting the needed comma or line ending with another not often used char, like # for example. So that when showing the data on screen all # chars could be converted to line endings and the inverse when storing data back to the database. The ReplaceString routine is useful here.<br />
<br />
<syntaxhighlight><br />
uses sdfdata, db;<br />
<br />
constructor TComponentsDatabase.Create;<br />
var<br />
FDataset: TSdfDataset;<br />
begin<br />
inherited Create;<br />
<br />
FDataset := TSdfDataset.Create(nil);<br />
FDataset.FileName := vConfigurations.ComponentsDBFile;<br />
<br />
// Not necessary with TSdfDataset<br />
// FDataset.TableName := STR_DB_COMPONENTS_TABLE;<br />
// FDataset.PrimaryKey := STR_DB_COMPONENTS_ID;<br />
<br />
// Adds field definitions<br />
FDataset.FieldDefs.Add('ID', ftString);<br />
FDataset.FieldDefs.Add('NAMEEN', ftString);<br />
FDataset.FieldDefs.Add('NAMEPT', ftString);<br />
FDataset.FieldDefs.Add('HEIGHT', ftString);<br />
FDataset.FieldDefs.Add('WIDTH', ftString);<br />
FDataset.FieldDefs.Add('PINS', ftString);<br />
FDataset.FieldDefs.Add('DRAWINGCODE', ftString);<br />
<br />
// Necessary for TSdfDataset<br />
FDataset.Delimiter := ',';<br />
FDataset.FirstLineAsSchema := True;<br />
<br />
FDataset.Active := True;<br />
<br />
// Sets the initial record<br />
CurrentRecNo := 1;<br />
FDataset.First;<br />
end;</syntaxhighlight><br />
<br />
When using TSdfDataset directly be aware that RecNo, although it is implemented, does not work as a way to move through the dataset whether reading or writing records. The standard navigation routines like First, Next, Prior and Last work as expected, so you need to use them rather than RecNo.<br />
If you are used to using absolute record numbers to navigate around a database you can implement your own version of RecNo. Declare a global longint variable called CurrentRecNo which will hold the current RecNo value. Remember that this variable will have the same convention as RecNo, so the first record has number 1 (it is not zero-based). After activating the database initialize the database to the first record with TSdfDataset.First and set CurrentRecNo := 1<br />
<br />
<syntaxhighlight>{@@<br />
Moves to the desired record using TDataset.Next and TDataset.Prior<br />
This avoids using TDataset.RecNo which doesn't navigate reliably in any dataset.<br />
<br />
@param AID Indicates the record number. The first record has number 1<br />
}<br />
procedure TComponentsDatabase.GoToRec(AID: Integer);<br />
begin<br />
// We are before the desired record, move forward<br />
if CurrentRecNo < AID then<br />
begin<br />
while (not FDataset.EOF) and (CurrentRecNo < AID) do<br />
begin<br />
FDataset.Next;<br />
FDataset.CursorPosChanged;<br />
Inc(CurrentRecNo);<br />
end;<br />
end<br />
// We are after the desired record, move back<br />
else if CurrentRecNo > AID then<br />
begin<br />
while (CurrentRecNo >= 1) and (CurrentRecNo > AID) do<br />
begin<br />
FDataset.Prior;<br />
FDataset.CursorPosChanged;<br />
Dec(CurrentRecNo);<br />
end;<br />
end;<br />
end;</syntaxhighlight><br />
<br />
=== Using with data-aware controls ===<br />
<br />
== Lazarus and Advantage Database Server ==<br />
* Please see [[Advantage Database Server]] for details on using Advantage Database Server<br />
<br />
==See also==<br />
(Sorted alphabetically)<br />
* [[Databases]]<br />
* [[Database_field_type]]<br />
* [[Firebird in action]]<br />
* [[How to write in-memory database applications in Lazarus/FPC]]<br />
* [[Lazarus DB Faq]]<br />
* [[Lazarus Tdbf Tutorial]]<br />
* [[MS Access]]<br />
* [[multi-tier_options_with_fpc|Multi-tier options with FPC]]<br />
* [[MySQLDatabases]]<br />
* [[ODBCConn]]<br />
* [[SQLdb Tutorial1]]<br />
* [[SqlDBHowto]]<br />
* [[SQLite]]<br />
* [[tiOPF]] - a free and open source Object Persistence Framework.<br />
* [[Zeos tutorial]]<br />
<br />
==External links==<br />
<br />
* [http://pdo.sourceforge.net Pascal Data Objects] - a database API that worked for both FPC and Delphi and utilises native MySQL libraries for version 4.1 and 5.0 and Firebird SQL 1.5, and 2.0. It's inspired by PHP's PDO class.<br />
* [http://lazaruszeos.blogspot.com Zeos+SQLite Tutorial] - Good tutorial using screenshots and screencasts it explain how to use SQLite and Zeos, spanish (google translate does a good work in translating it to english)<br />
<br />
<br />
[[Category:Databases]]<br />
[[Category:Tutorials]]</div>Mario13https://wiki.freepascal.org/index.php?title=Lazarus_Database_Overview&diff=66013Lazarus Database Overview2013-02-18T20:02:28Z<p>Mario13: /* Lazarus and Paradox */</p>
<hr />
<div>{{Translate}}<br />
<br />
== Overview ==<br />
<br />
This article is an overview of the which databases can work with Lazarus.<br />
<br />
Lazarus supports several databases out of the box (using e.g. the SQLDB framework), however the developer must install the required packages (client libraries) for each one. <br />
<br />
You can access the database through code or by dropping components on a form. The data-aware components represent fields and are connected by setting the DataSource property to point to a TDataSource. The Datasource represents a table and is connected to the database components (examples: ''TPSQLDatabase'', ''TSQLiteDataSet'') by setting the DataSet property. The data-aware components are located on the "Data Controls" tab. The Datasource and the database controls are located on the "Data Access" tab.<br />
<br />
== Lazarus and Interbase / Firebird ==<br />
* Please see [[Firebird_in_action|Firebird in action]] for details on various access methods, which include<br />
# Built-in SQLDB support<br />
# FBLib<br />
# IBX<br />
# PDO<br />
# Zeos<br />
<br />
For a tutorial that leads you through creating a Lazarus GUI for a Firebird database, see:<br />
* [[SQLdb Tutorial1]]<br />
<br />
<br />
== Lazarus and MySQL ==<br />
* Please see [[mysql]] for details on various access methods, which include:<br />
# Built-in SQLDB support<br />
# PDO<br />
# Zeos<br />
<br />
== Lazarus and MSSQL/Sybase ==<br />
You can connect to Microsoft SQL Server databases using<br />
# The built-in '''SQLdb''' (recent Lazarus/FPC 2.6.1+): '''TMSSQLConnection''' (MS SQL) and '''TSybaseConnection''' (Sybase ASE)<br />
## On Windows, you can download a recent 32 or 64 bit version of the FreeTDS library '''dblib.dll''' here: [ftp://ftp.freepascal.org/fpc/contrib/windows/]<br />
## Not necessary normally: By modifying FPC file '''dblib.pas''' SQLDB could use the "native" library '''ntwdblib.dll''' instead of the default FreeTDS library '''dblib.dll''' (in this case FPC needs to be recompiled).<br />
## On Linux by default it uses the FreeTDS library '''libsybdb.so''' (for example, in Debian is in package '''libsybd5''').<br />
# '''Zeos''' component '''TZConnection''' (latest CVS, see links to Zeos elsewhere on this page)<br />
## On Windows you can choose between native library '''ntwdblib.dll''' (protocol '''mssql''') or FreeTDS libraries (protocol '''FreeTDS_MsSQL-nnnn''') where nnnn is one of four variants depending on the server version. For Delphi (not Lazarus) there is also another Zeos protocol '''ado''' for MSSQL 2005 or later. Using protocols mssql or ado generates code not platform independient.<br />
## On Linux the only way is with FreeTDS protocols and libraries (you should use '''libsybdb.so''').<br />
# '''ODBC''' (MSSQL and Sybase ASE) with SQLdb '''TODBCConnection''' (see also [http://wiki.freepascal.org/ODBCConn#Connecting_to_Microsoft_SQL_Server])<br />
## On Windows it uses native ODBC Microsoft libraries (like sqlsrv32.dll for MSSQL 2000)<br />
## On Linux it uses unixODBC + FreeTDS (packages unixodbc or iodbc, and tdsodbc). Since 2012 there is also a Microsoft SQL Server ODBC Driver 1.0 for Linux which is a binary product (no open source) and provides native connectivity, but was released only for 64 bits and only for RedHat.<br />
<br />
Please see the FPC and Lazarus help files for details on using SQLDB with Sybase ASE and MSSQL Server.<br />
<br />
{{Note| In any of the above forms, you can connect using TCP/IP, e.g. on port 1433. }}<br />
<br />
If you use native Microsoft Libraries (over Windows) it could be possible to connect to remote server with Named Pipes. FreeTDS libraries do not support Named Pipes.<br />
<br />
{{Note| Lazarus 1.0 was released with FPC 2.6.0 and does not include TMSSQLConnection or TSybaseConnection. If you want these, it might be easiest to download a snapshot of the latest Lazarus built with FPC 2.6.1, optinally installing that in a directory different from your Lazarus 1.0 version. You can use --primary-config-path to set up a separate environment for the Lazarus snapshot (see [[Multiple Lazarus]]) }}<br />
<br />
== Lazarus and ODBC ==<br />
ODBC is a general database connection standard which is available on Linux, Windows and OSX. You will need an ODBC driver from your database vendor and set up an ODBC "data source" (also known as DSN).<br />
You can use the SQLDB components (TODBCConnection) to connect to an ODBC data soruce.<br />
See [[ODBCConn]] for more details and examples<br />
<br />
== Lazarus and Oracle ==<br />
* Acces methods include:<br />
# Built-in SQLDB support<br />
# Zeos<br />
<br />
== Lazarus and PostgreSQL ==<br />
* Please see [[postgres]] for details on various access methods, which include:<br />
# Built-in SQLdb support. Use component '''TPQConnection''' from palette '''SQLdb'''<br />
# Zeos. Use component '''TZConnection''' with protocol 'postgresql' from palette '''Zeos Access'''<br />
<br />
== Lazarus and SQLite ==<br />
SQLite is an embedded database; the database code can be distributed as a library (.dll/.so/.dylib) with your application to make it self-contained (comparable to Firebird embedded). SQLite is quite popular due to its relative simplicity, speed, small size and cross-platform support.<br />
<br />
Please see the [[SQLite]] page for details on various access methods, which include:<br />
# Built-in SQLDb support<br />
# Zeos<br />
# SQLitePass <br />
# TSQLite3Dataset<br />
<br />
== Lazarus and dBase ==<br />
<br />
FPC includes a simple database component that is derived from the Delphi TTable component called "TDbf" [http://tdbf.sourceforge.net/ TDbf Website]). It supports various DBase and Foxpro formats.<br />
<br />
TDbf does not accept SQL commands but you can use the dataset methods etc and you can also use regular databound controls such as the DBGrid.<br />
<br />
It doesn't require any sort of runtime database engine. However it's not the best option for large database applications.<br />
<br />
See the [[Lazarus Tdbf Tutorial|TDbf Tutorial page]] for the tutorial as well as documentation.<br />
<br />
You can use e.g. OpenOffice/LibreOffice Base to visually create/edit dbf files.<br />
<br />
When this code is run, your DVD collection table will be created. After that, all data aware components linked through the TDatasource to this component will allow easy access to the data.<br />
<br />
<br />
== Lazarus and Paradox ==<br />
<br />
Paradox was the default format for table files in Delphi and before (view [http://en.wikipedia.org/wiki/Paradox_%28database%29 Wikipedia]).<br />
The concept is similar to DBF's, where the "database" is a folder, and each table is a "file" inside that folder. Also, each index is a file too.<br />
To access this files from Lazarus we have this options:<br />
<br />
* '''TParadox''': Install package "lazparadox 0.0" included in the standard distribution. When you install this package, you will see a new component labeled "PDX" in the "Data Access" palette. In order to use this component you have to include "paradox" in the uses list. This component is not standalon, it uses a "native" library, namely the [http://pxlib.sourceforge.net pdxlib library] which is available for Linux. Alternatively for example in Debian, you could to install '''pxlib1''' from package manager.<br />
<br />
* '''TPdx''': Paradox DataSet for Lazarus and Delphi from [http://tpdx.sourceforge.net/ this site]. This component is standalone (pure object pascal), not requiring any external library. The package to install is "paradoxlaz.lpk" and the component should appear in the "Data Access" palette. <br />
<br />
* '''TParadoxDataSet''': is a TDataSet that can only read Paradox Files up to Version 7. See this [http://wiki.lazarus.freepascal.org/TParadoxDataSet wiki page]. The approach is similar to the TPdx component, the package to install is "lazparadox.lpk" and the component should also appear in the "Data Access" palette.<br />
<br />
== Using TSdfDataset and TFixedDataset ==<br />
<br />
TSdfDataset and TFixedDataset are two simple datasets which offer a very simple textual storage format. These datasets are very convenient for small databases, because they are fully implemented as an object pascal unit, and thus require no external libraries, and because their textual format allows them to be easely edited with a text editor.<br />
<br />
Note: December 2012/FPC 2.7.1: SDFDataset is supposed to read/write CSV files according to RFC4180, but still has some problems with quoted fields etc. For more details, see [[CSV]]<br />
<br />
To start with this format, a initial database file should be created. The format is very simple, so use a text editor to do this.<br />
<br />
Bellow is a sample database for TSdfDataset. Note that the first line has the names of the fields and that we are using commas as separators:<br />
<br />
<pre>ID,NAMEEN,NAMEPT,HEIGHT,WIDTH,PINS,DRAWINGCODE<br />
1,resistor,resistor,1,1,1,LINE<br />
2,capacitor,capacitor,1,1,1,LINE<br />
3,transistor npn,transistor npn</pre><br />
<br />
And here is an example database for using with TFixedDataset. Each record occupies a fixed amount of space, and if the field is smaller then it, spaces should be used to fill the remaining size.<br />
<br />
<pre>Name = 15 chars; Surname = 15 chars; Tell = 10 chars; e_mail = 20 chars;<br />
Piet Pompies piet@pompies.net</pre><br />
<br />
=== Using the datasets directly ===<br />
<br />
Sometimes it is useful to create the dataset and work with it completely in code, and the following code will do exactly this. Note some peculiarities of TSdfDataset/TFixedDataset:<br />
<br />
* The lines in the database can have a maximum size of about 300. A fix is being researched.<br />
* It is necessary to add the field definitions. Some datasets are able to fill this information alone from the database file<br />
* One should set FirstLineAsSchema to true, to indicate that the first line includes the field names and positions<br />
* The Delimiter property holds the separator for the fields. It will not be possible to use this char in strings in the database. Similarly it will not be possible to have lineendings in the database because they mark the change between records. It's possible to overcome this by substituting the needed comma or line ending with another not often used char, like # for example. So that when showing the data on screen all # chars could be converted to line endings and the inverse when storing data back to the database. The ReplaceString routine is useful here.<br />
<br />
<syntaxhighlight><br />
uses sdfdata, db;<br />
<br />
constructor TComponentsDatabase.Create;<br />
var<br />
FDataset: TSdfDataset;<br />
begin<br />
inherited Create;<br />
<br />
FDataset := TSdfDataset.Create(nil);<br />
FDataset.FileName := vConfigurations.ComponentsDBFile;<br />
<br />
// Not necessary with TSdfDataset<br />
// FDataset.TableName := STR_DB_COMPONENTS_TABLE;<br />
// FDataset.PrimaryKey := STR_DB_COMPONENTS_ID;<br />
<br />
// Adds field definitions<br />
FDataset.FieldDefs.Add('ID', ftString);<br />
FDataset.FieldDefs.Add('NAMEEN', ftString);<br />
FDataset.FieldDefs.Add('NAMEPT', ftString);<br />
FDataset.FieldDefs.Add('HEIGHT', ftString);<br />
FDataset.FieldDefs.Add('WIDTH', ftString);<br />
FDataset.FieldDefs.Add('PINS', ftString);<br />
FDataset.FieldDefs.Add('DRAWINGCODE', ftString);<br />
<br />
// Necessary for TSdfDataset<br />
FDataset.Delimiter := ',';<br />
FDataset.FirstLineAsSchema := True;<br />
<br />
FDataset.Active := True;<br />
<br />
// Sets the initial record<br />
CurrentRecNo := 1;<br />
FDataset.First;<br />
end;</syntaxhighlight><br />
<br />
When using TSdfDataset directly be aware that RecNo, although it is implemented, does not work as a way to move through the dataset whether reading or writing records. The standard navigation routines like First, Next, Prior and Last work as expected, so you need to use them rather than RecNo.<br />
If you are used to using absolute record numbers to navigate around a database you can implement your own version of RecNo. Declare a global longint variable called CurrentRecNo which will hold the current RecNo value. Remember that this variable will have the same convention as RecNo, so the first record has number 1 (it is not zero-based). After activating the database initialize the database to the first record with TSdfDataset.First and set CurrentRecNo := 1<br />
<br />
<syntaxhighlight>{@@<br />
Moves to the desired record using TDataset.Next and TDataset.Prior<br />
This avoids using TDataset.RecNo which doesn't navigate reliably in any dataset.<br />
<br />
@param AID Indicates the record number. The first record has number 1<br />
}<br />
procedure TComponentsDatabase.GoToRec(AID: Integer);<br />
begin<br />
// We are before the desired record, move forward<br />
if CurrentRecNo < AID then<br />
begin<br />
while (not FDataset.EOF) and (CurrentRecNo < AID) do<br />
begin<br />
FDataset.Next;<br />
FDataset.CursorPosChanged;<br />
Inc(CurrentRecNo);<br />
end;<br />
end<br />
// We are after the desired record, move back<br />
else if CurrentRecNo > AID then<br />
begin<br />
while (CurrentRecNo >= 1) and (CurrentRecNo > AID) do<br />
begin<br />
FDataset.Prior;<br />
FDataset.CursorPosChanged;<br />
Dec(CurrentRecNo);<br />
end;<br />
end;<br />
end;</syntaxhighlight><br />
<br />
=== Using with data-aware controls ===<br />
<br />
== Lazarus and Advantage Database Server ==<br />
* Please see [[Advantage Database Server]] for details on using Advantage Database Server<br />
<br />
==See also==<br />
(Sorted alphabetically)<br />
* [[Databases]]<br />
* [[Database_field_type]]<br />
* [[Firebird in action]]<br />
* [[How to write in-memory database applications in Lazarus/FPC]]<br />
* [[Lazarus DB Faq]]<br />
* [[Lazarus Tdbf Tutorial]]<br />
* [[MS Access]]<br />
* [[multi-tier_options_with_fpc|Multi-tier options with FPC]]<br />
* [[MySQLDatabases]]<br />
* [[ODBCConn]]<br />
* [[SQLdb Tutorial1]]<br />
* [[SqlDBHowto]]<br />
* [[SQLite]]<br />
* [[tiOPF]] - a free and open source Object Persistence Framework.<br />
* [[Zeos tutorial]]<br />
<br />
==External links==<br />
<br />
* [http://pdo.sourceforge.net Pascal Data Objects] - a database API that worked for both FPC and Delphi and utilises native MySQL libraries for version 4.1 and 5.0 and Firebird SQL 1.5, and 2.0. It's inspired by PHP's PDO class.<br />
* [http://lazaruszeos.blogspot.com Zeos+SQLite Tutorial] - Good tutorial using screenshots and screencasts it explain how to use SQLite and Zeos, spanish (google translate does a good work in translating it to english)<br />
<br />
<br />
[[Category:Databases]]<br />
[[Category:Tutorials]]</div>Mario13https://wiki.freepascal.org/index.php?title=Lazarus_Database_Overview&diff=66012Lazarus Database Overview2013-02-18T19:53:47Z<p>Mario13: /* Lazarus and Paradox */</p>
<hr />
<div>{{Translate}}<br />
<br />
== Overview ==<br />
<br />
This article is an overview of the which databases can work with Lazarus.<br />
<br />
Lazarus supports several databases out of the box (using e.g. the SQLDB framework), however the developer must install the required packages (client libraries) for each one. <br />
<br />
You can access the database through code or by dropping components on a form. The data-aware components represent fields and are connected by setting the DataSource property to point to a TDataSource. The Datasource represents a table and is connected to the database components (examples: ''TPSQLDatabase'', ''TSQLiteDataSet'') by setting the DataSet property. The data-aware components are located on the "Data Controls" tab. The Datasource and the database controls are located on the "Data Access" tab.<br />
<br />
== Lazarus and Interbase / Firebird ==<br />
* Please see [[Firebird_in_action|Firebird in action]] for details on various access methods, which include<br />
# Built-in SQLDB support<br />
# FBLib<br />
# IBX<br />
# PDO<br />
# Zeos<br />
<br />
For a tutorial that leads you through creating a Lazarus GUI for a Firebird database, see:<br />
* [[SQLdb Tutorial1]]<br />
<br />
<br />
== Lazarus and MySQL ==<br />
* Please see [[mysql]] for details on various access methods, which include:<br />
# Built-in SQLDB support<br />
# PDO<br />
# Zeos<br />
<br />
== Lazarus and MSSQL/Sybase ==<br />
You can connect to Microsoft SQL Server databases using<br />
# The built-in '''SQLdb''' (recent Lazarus/FPC 2.6.1+): '''TMSSQLConnection''' (MS SQL) and '''TSybaseConnection''' (Sybase ASE)<br />
## On Windows, you can download a recent 32 or 64 bit version of the FreeTDS library '''dblib.dll''' here: [ftp://ftp.freepascal.org/fpc/contrib/windows/]<br />
## Not necessary normally: By modifying FPC file '''dblib.pas''' SQLDB could use the "native" library '''ntwdblib.dll''' instead of the default FreeTDS library '''dblib.dll''' (in this case FPC needs to be recompiled).<br />
## On Linux by default it uses the FreeTDS library '''libsybdb.so''' (for example, in Debian is in package '''libsybd5''').<br />
# '''Zeos''' component '''TZConnection''' (latest CVS, see links to Zeos elsewhere on this page)<br />
## On Windows you can choose between native library '''ntwdblib.dll''' (protocol '''mssql''') or FreeTDS libraries (protocol '''FreeTDS_MsSQL-nnnn''') where nnnn is one of four variants depending on the server version. For Delphi (not Lazarus) there is also another Zeos protocol '''ado''' for MSSQL 2005 or later. Using protocols mssql or ado generates code not platform independient.<br />
## On Linux the only way is with FreeTDS protocols and libraries (you should use '''libsybdb.so''').<br />
# '''ODBC''' (MSSQL and Sybase ASE) with SQLdb '''TODBCConnection''' (see also [http://wiki.freepascal.org/ODBCConn#Connecting_to_Microsoft_SQL_Server])<br />
## On Windows it uses native ODBC Microsoft libraries (like sqlsrv32.dll for MSSQL 2000)<br />
## On Linux it uses unixODBC + FreeTDS (packages unixodbc or iodbc, and tdsodbc). Since 2012 there is also a Microsoft SQL Server ODBC Driver 1.0 for Linux which is a binary product (no open source) and provides native connectivity, but was released only for 64 bits and only for RedHat.<br />
<br />
Please see the FPC and Lazarus help files for details on using SQLDB with Sybase ASE and MSSQL Server.<br />
<br />
{{Note| In any of the above forms, you can connect using TCP/IP, e.g. on port 1433. }}<br />
<br />
If you use native Microsoft Libraries (over Windows) it could be possible to connect to remote server with Named Pipes. FreeTDS libraries do not support Named Pipes.<br />
<br />
{{Note| Lazarus 1.0 was released with FPC 2.6.0 and does not include TMSSQLConnection or TSybaseConnection. If you want these, it might be easiest to download a snapshot of the latest Lazarus built with FPC 2.6.1, optinally installing that in a directory different from your Lazarus 1.0 version. You can use --primary-config-path to set up a separate environment for the Lazarus snapshot (see [[Multiple Lazarus]]) }}<br />
<br />
== Lazarus and ODBC ==<br />
ODBC is a general database connection standard which is available on Linux, Windows and OSX. You will need an ODBC driver from your database vendor and set up an ODBC "data source" (also known as DSN).<br />
You can use the SQLDB components (TODBCConnection) to connect to an ODBC data soruce.<br />
See [[ODBCConn]] for more details and examples<br />
<br />
== Lazarus and Oracle ==<br />
* Acces methods include:<br />
# Built-in SQLDB support<br />
# Zeos<br />
<br />
== Lazarus and PostgreSQL ==<br />
* Please see [[postgres]] for details on various access methods, which include:<br />
# Built-in SQLdb support. Use component '''TPQConnection''' from palette '''SQLdb'''<br />
# Zeos. Use component '''TZConnection''' with protocol 'postgresql' from palette '''Zeos Access'''<br />
<br />
== Lazarus and SQLite ==<br />
SQLite is an embedded database; the database code can be distributed as a library (.dll/.so/.dylib) with your application to make it self-contained (comparable to Firebird embedded). SQLite is quite popular due to its relative simplicity, speed, small size and cross-platform support.<br />
<br />
Please see the [[SQLite]] page for details on various access methods, which include:<br />
# Built-in SQLDb support<br />
# Zeos<br />
# SQLitePass <br />
# TSQLite3Dataset<br />
<br />
== Lazarus and dBase ==<br />
<br />
FPC includes a simple database component that is derived from the Delphi TTable component called "TDbf" [http://tdbf.sourceforge.net/ TDbf Website]). It supports various DBase and Foxpro formats.<br />
<br />
TDbf does not accept SQL commands but you can use the dataset methods etc and you can also use regular databound controls such as the DBGrid.<br />
<br />
It doesn't require any sort of runtime database engine. However it's not the best option for large database applications.<br />
<br />
See the [[Lazarus Tdbf Tutorial|TDbf Tutorial page]] for the tutorial as well as documentation.<br />
<br />
You can use e.g. OpenOffice/LibreOffice Base to visually create/edit dbf files.<br />
<br />
When this code is run, your DVD collection table will be created. After that, all data aware components linked through the TDatasource to this component will allow easy access to the data.<br />
<br />
<br />
== Lazarus and Paradox ==<br />
<br />
Paradox was the default format for table files in Delphi and before (view [http://en.wikipedia.org/wiki/Paradox_%28database%29 Wikipedia]).<br />
The concept is similar to DBF's, where the "database" is a folder, and each table is in a "file" inside that folder. Also, each index is a file too.<br />
To access this files from Lazarus:<br />
<br />
* '''TParadox''': Install package "lazparadox 0.0" included in the standard distribution. When you install this package, you will see a new component labeled "PDX" in the "Data Access" palette. In order to use this component you have to include "paradox" in the uses list. This component is not standalon, it uses a "native" library, namely the [http://pxlib.sourceforge.net pdxlib library] which is available for Linux. Alternatively for example in Debian, you could to install '''pxlib1''' from package manager.<br />
<br />
* '''TPdx''': Paradox DataSet for Lazarus and Delphi from [http://tpdx.sourceforge.net/ this site]. This component is standalone (pure object pascal), not requiring any external library.<br />
<br />
* '''TParadoxDataSet''': is a TDataSet that can only read Paradox Files up to Version 7. See this [http://wiki.lazarus.freepascal.org/TParadoxDataSet wiki page].<br />
<br />
== Using TSdfDataset and TFixedDataset ==<br />
<br />
TSdfDataset and TFixedDataset are two simple datasets which offer a very simple textual storage format. These datasets are very convenient for small databases, because they are fully implemented as an object pascal unit, and thus require no external libraries, and because their textual format allows them to be easely edited with a text editor.<br />
<br />
Note: December 2012/FPC 2.7.1: SDFDataset is supposed to read/write CSV files according to RFC4180, but still has some problems with quoted fields etc. For more details, see [[CSV]]<br />
<br />
To start with this format, a initial database file should be created. The format is very simple, so use a text editor to do this.<br />
<br />
Bellow is a sample database for TSdfDataset. Note that the first line has the names of the fields and that we are using commas as separators:<br />
<br />
<pre>ID,NAMEEN,NAMEPT,HEIGHT,WIDTH,PINS,DRAWINGCODE<br />
1,resistor,resistor,1,1,1,LINE<br />
2,capacitor,capacitor,1,1,1,LINE<br />
3,transistor npn,transistor npn</pre><br />
<br />
And here is an example database for using with TFixedDataset. Each record occupies a fixed amount of space, and if the field is smaller then it, spaces should be used to fill the remaining size.<br />
<br />
<pre>Name = 15 chars; Surname = 15 chars; Tell = 10 chars; e_mail = 20 chars;<br />
Piet Pompies piet@pompies.net</pre><br />
<br />
=== Using the datasets directly ===<br />
<br />
Sometimes it is useful to create the dataset and work with it completely in code, and the following code will do exactly this. Note some peculiarities of TSdfDataset/TFixedDataset:<br />
<br />
* The lines in the database can have a maximum size of about 300. A fix is being researched.<br />
* It is necessary to add the field definitions. Some datasets are able to fill this information alone from the database file<br />
* One should set FirstLineAsSchema to true, to indicate that the first line includes the field names and positions<br />
* The Delimiter property holds the separator for the fields. It will not be possible to use this char in strings in the database. Similarly it will not be possible to have lineendings in the database because they mark the change between records. It's possible to overcome this by substituting the needed comma or line ending with another not often used char, like # for example. So that when showing the data on screen all # chars could be converted to line endings and the inverse when storing data back to the database. The ReplaceString routine is useful here.<br />
<br />
<syntaxhighlight><br />
uses sdfdata, db;<br />
<br />
constructor TComponentsDatabase.Create;<br />
var<br />
FDataset: TSdfDataset;<br />
begin<br />
inherited Create;<br />
<br />
FDataset := TSdfDataset.Create(nil);<br />
FDataset.FileName := vConfigurations.ComponentsDBFile;<br />
<br />
// Not necessary with TSdfDataset<br />
// FDataset.TableName := STR_DB_COMPONENTS_TABLE;<br />
// FDataset.PrimaryKey := STR_DB_COMPONENTS_ID;<br />
<br />
// Adds field definitions<br />
FDataset.FieldDefs.Add('ID', ftString);<br />
FDataset.FieldDefs.Add('NAMEEN', ftString);<br />
FDataset.FieldDefs.Add('NAMEPT', ftString);<br />
FDataset.FieldDefs.Add('HEIGHT', ftString);<br />
FDataset.FieldDefs.Add('WIDTH', ftString);<br />
FDataset.FieldDefs.Add('PINS', ftString);<br />
FDataset.FieldDefs.Add('DRAWINGCODE', ftString);<br />
<br />
// Necessary for TSdfDataset<br />
FDataset.Delimiter := ',';<br />
FDataset.FirstLineAsSchema := True;<br />
<br />
FDataset.Active := True;<br />
<br />
// Sets the initial record<br />
CurrentRecNo := 1;<br />
FDataset.First;<br />
end;</syntaxhighlight><br />
<br />
When using TSdfDataset directly be aware that RecNo, although it is implemented, does not work as a way to move through the dataset whether reading or writing records. The standard navigation routines like First, Next, Prior and Last work as expected, so you need to use them rather than RecNo.<br />
If you are used to using absolute record numbers to navigate around a database you can implement your own version of RecNo. Declare a global longint variable called CurrentRecNo which will hold the current RecNo value. Remember that this variable will have the same convention as RecNo, so the first record has number 1 (it is not zero-based). After activating the database initialize the database to the first record with TSdfDataset.First and set CurrentRecNo := 1<br />
<br />
<syntaxhighlight>{@@<br />
Moves to the desired record using TDataset.Next and TDataset.Prior<br />
This avoids using TDataset.RecNo which doesn't navigate reliably in any dataset.<br />
<br />
@param AID Indicates the record number. The first record has number 1<br />
}<br />
procedure TComponentsDatabase.GoToRec(AID: Integer);<br />
begin<br />
// We are before the desired record, move forward<br />
if CurrentRecNo < AID then<br />
begin<br />
while (not FDataset.EOF) and (CurrentRecNo < AID) do<br />
begin<br />
FDataset.Next;<br />
FDataset.CursorPosChanged;<br />
Inc(CurrentRecNo);<br />
end;<br />
end<br />
// We are after the desired record, move back<br />
else if CurrentRecNo > AID then<br />
begin<br />
while (CurrentRecNo >= 1) and (CurrentRecNo > AID) do<br />
begin<br />
FDataset.Prior;<br />
FDataset.CursorPosChanged;<br />
Dec(CurrentRecNo);<br />
end;<br />
end;<br />
end;</syntaxhighlight><br />
<br />
=== Using with data-aware controls ===<br />
<br />
== Lazarus and Advantage Database Server ==<br />
* Please see [[Advantage Database Server]] for details on using Advantage Database Server<br />
<br />
==See also==<br />
(Sorted alphabetically)<br />
* [[Databases]]<br />
* [[Database_field_type]]<br />
* [[Firebird in action]]<br />
* [[How to write in-memory database applications in Lazarus/FPC]]<br />
* [[Lazarus DB Faq]]<br />
* [[Lazarus Tdbf Tutorial]]<br />
* [[MS Access]]<br />
* [[multi-tier_options_with_fpc|Multi-tier options with FPC]]<br />
* [[MySQLDatabases]]<br />
* [[ODBCConn]]<br />
* [[SQLdb Tutorial1]]<br />
* [[SqlDBHowto]]<br />
* [[SQLite]]<br />
* [[tiOPF]] - a free and open source Object Persistence Framework.<br />
* [[Zeos tutorial]]<br />
<br />
==External links==<br />
<br />
* [http://pdo.sourceforge.net Pascal Data Objects] - a database API that worked for both FPC and Delphi and utilises native MySQL libraries for version 4.1 and 5.0 and Firebird SQL 1.5, and 2.0. It's inspired by PHP's PDO class.<br />
* [http://lazaruszeos.blogspot.com Zeos+SQLite Tutorial] - Good tutorial using screenshots and screencasts it explain how to use SQLite and Zeos, spanish (google translate does a good work in translating it to english)<br />
<br />
<br />
[[Category:Databases]]<br />
[[Category:Tutorials]]</div>Mario13https://wiki.freepascal.org/index.php?title=Lazarus_Database_Overview&diff=66011Lazarus Database Overview2013-02-18T19:44:23Z<p>Mario13: /* Lazarus and Paradox */</p>
<hr />
<div>{{Translate}}<br />
<br />
== Overview ==<br />
<br />
This article is an overview of the which databases can work with Lazarus.<br />
<br />
Lazarus supports several databases out of the box (using e.g. the SQLDB framework), however the developer must install the required packages (client libraries) for each one. <br />
<br />
You can access the database through code or by dropping components on a form. The data-aware components represent fields and are connected by setting the DataSource property to point to a TDataSource. The Datasource represents a table and is connected to the database components (examples: ''TPSQLDatabase'', ''TSQLiteDataSet'') by setting the DataSet property. The data-aware components are located on the "Data Controls" tab. The Datasource and the database controls are located on the "Data Access" tab.<br />
<br />
== Lazarus and Interbase / Firebird ==<br />
* Please see [[Firebird_in_action|Firebird in action]] for details on various access methods, which include<br />
# Built-in SQLDB support<br />
# FBLib<br />
# IBX<br />
# PDO<br />
# Zeos<br />
<br />
For a tutorial that leads you through creating a Lazarus GUI for a Firebird database, see:<br />
* [[SQLdb Tutorial1]]<br />
<br />
<br />
== Lazarus and MySQL ==<br />
* Please see [[mysql]] for details on various access methods, which include:<br />
# Built-in SQLDB support<br />
# PDO<br />
# Zeos<br />
<br />
== Lazarus and MSSQL/Sybase ==<br />
You can connect to Microsoft SQL Server databases using<br />
# The built-in '''SQLdb''' (recent Lazarus/FPC 2.6.1+): '''TMSSQLConnection''' (MS SQL) and '''TSybaseConnection''' (Sybase ASE)<br />
## On Windows, you can download a recent 32 or 64 bit version of the FreeTDS library '''dblib.dll''' here: [ftp://ftp.freepascal.org/fpc/contrib/windows/]<br />
## Not necessary normally: By modifying FPC file '''dblib.pas''' SQLDB could use the "native" library '''ntwdblib.dll''' instead of the default FreeTDS library '''dblib.dll''' (in this case FPC needs to be recompiled).<br />
## On Linux by default it uses the FreeTDS library '''libsybdb.so''' (for example, in Debian is in package '''libsybd5''').<br />
# '''Zeos''' component '''TZConnection''' (latest CVS, see links to Zeos elsewhere on this page)<br />
## On Windows you can choose between native library '''ntwdblib.dll''' (protocol '''mssql''') or FreeTDS libraries (protocol '''FreeTDS_MsSQL-nnnn''') where nnnn is one of four variants depending on the server version. For Delphi (not Lazarus) there is also another Zeos protocol '''ado''' for MSSQL 2005 or later. Using protocols mssql or ado generates code not platform independient.<br />
## On Linux the only way is with FreeTDS protocols and libraries (you should use '''libsybdb.so''').<br />
# '''ODBC''' (MSSQL and Sybase ASE) with SQLdb '''TODBCConnection''' (see also [http://wiki.freepascal.org/ODBCConn#Connecting_to_Microsoft_SQL_Server])<br />
## On Windows it uses native ODBC Microsoft libraries (like sqlsrv32.dll for MSSQL 2000)<br />
## On Linux it uses unixODBC + FreeTDS (packages unixodbc or iodbc, and tdsodbc). Since 2012 there is also a Microsoft SQL Server ODBC Driver 1.0 for Linux which is a binary product (no open source) and provides native connectivity, but was released only for 64 bits and only for RedHat.<br />
<br />
Please see the FPC and Lazarus help files for details on using SQLDB with Sybase ASE and MSSQL Server.<br />
<br />
{{Note| In any of the above forms, you can connect using TCP/IP, e.g. on port 1433. }}<br />
<br />
If you use native Microsoft Libraries (over Windows) it could be possible to connect to remote server with Named Pipes. FreeTDS libraries do not support Named Pipes.<br />
<br />
{{Note| Lazarus 1.0 was released with FPC 2.6.0 and does not include TMSSQLConnection or TSybaseConnection. If you want these, it might be easiest to download a snapshot of the latest Lazarus built with FPC 2.6.1, optinally installing that in a directory different from your Lazarus 1.0 version. You can use --primary-config-path to set up a separate environment for the Lazarus snapshot (see [[Multiple Lazarus]]) }}<br />
<br />
== Lazarus and ODBC ==<br />
ODBC is a general database connection standard which is available on Linux, Windows and OSX. You will need an ODBC driver from your database vendor and set up an ODBC "data source" (also known as DSN).<br />
You can use the SQLDB components (TODBCConnection) to connect to an ODBC data soruce.<br />
See [[ODBCConn]] for more details and examples<br />
<br />
== Lazarus and Oracle ==<br />
* Acces methods include:<br />
# Built-in SQLDB support<br />
# Zeos<br />
<br />
== Lazarus and PostgreSQL ==<br />
* Please see [[postgres]] for details on various access methods, which include:<br />
# Built-in SQLdb support. Use component '''TPQConnection''' from palette '''SQLdb'''<br />
# Zeos. Use component '''TZConnection''' with protocol 'postgresql' from palette '''Zeos Access'''<br />
<br />
== Lazarus and SQLite ==<br />
SQLite is an embedded database; the database code can be distributed as a library (.dll/.so/.dylib) with your application to make it self-contained (comparable to Firebird embedded). SQLite is quite popular due to its relative simplicity, speed, small size and cross-platform support.<br />
<br />
Please see the [[SQLite]] page for details on various access methods, which include:<br />
# Built-in SQLDb support<br />
# Zeos<br />
# SQLitePass <br />
# TSQLite3Dataset<br />
<br />
== Lazarus and dBase ==<br />
<br />
FPC includes a simple database component that is derived from the Delphi TTable component called "TDbf" [http://tdbf.sourceforge.net/ TDbf Website]). It supports various DBase and Foxpro formats.<br />
<br />
TDbf does not accept SQL commands but you can use the dataset methods etc and you can also use regular databound controls such as the DBGrid.<br />
<br />
It doesn't require any sort of runtime database engine. However it's not the best option for large database applications.<br />
<br />
See the [[Lazarus Tdbf Tutorial|TDbf Tutorial page]] for the tutorial as well as documentation.<br />
<br />
You can use e.g. OpenOffice/LibreOffice Base to visually create/edit dbf files.<br />
<br />
When this code is run, your DVD collection table will be created. After that, all data aware components linked through the TDatasource to this component will allow easy access to the data.<br />
<br />
<br />
== Lazarus and Paradox ==<br />
<br />
Paradox was the default format for table files in Delphi and before (view [http://en.wikipedia.org/wiki/Paradox_%28database%29 Wikipedia]).<br />
The concept is similar to DBF's, where the "database" is a folder, and each table is in a "file" inside that folder. Also, each index is a file too.<br />
To access this files from Lazarus:<br />
* '''TParadox''': Install package "lazparadox 0.0" included in the standard distribution. When you install this package, you will see a new component labeled "PDX" in the "Data Access" palette. In order to use this component you have to include "paradox" in the uses list. This component uses the [http://pxlib.sourceforge.net pdxlib library] which is availble in this site for Linux. Alternatively for example in Debian, you could to install '''pxlib1''' from package manager.<br />
<br />
== Using TSdfDataset and TFixedDataset ==<br />
<br />
TSdfDataset and TFixedDataset are two simple datasets which offer a very simple textual storage format. These datasets are very convenient for small databases, because they are fully implemented as an object pascal unit, and thus require no external libraries, and because their textual format allows them to be easely edited with a text editor.<br />
<br />
Note: December 2012/FPC 2.7.1: SDFDataset is supposed to read/write CSV files according to RFC4180, but still has some problems with quoted fields etc. For more details, see [[CSV]]<br />
<br />
To start with this format, a initial database file should be created. The format is very simple, so use a text editor to do this.<br />
<br />
Bellow is a sample database for TSdfDataset. Note that the first line has the names of the fields and that we are using commas as separators:<br />
<br />
<pre>ID,NAMEEN,NAMEPT,HEIGHT,WIDTH,PINS,DRAWINGCODE<br />
1,resistor,resistor,1,1,1,LINE<br />
2,capacitor,capacitor,1,1,1,LINE<br />
3,transistor npn,transistor npn</pre><br />
<br />
And here is an example database for using with TFixedDataset. Each record occupies a fixed amount of space, and if the field is smaller then it, spaces should be used to fill the remaining size.<br />
<br />
<pre>Name = 15 chars; Surname = 15 chars; Tell = 10 chars; e_mail = 20 chars;<br />
Piet Pompies piet@pompies.net</pre><br />
<br />
=== Using the datasets directly ===<br />
<br />
Sometimes it is useful to create the dataset and work with it completely in code, and the following code will do exactly this. Note some peculiarities of TSdfDataset/TFixedDataset:<br />
<br />
* The lines in the database can have a maximum size of about 300. A fix is being researched.<br />
* It is necessary to add the field definitions. Some datasets are able to fill this information alone from the database file<br />
* One should set FirstLineAsSchema to true, to indicate that the first line includes the field names and positions<br />
* The Delimiter property holds the separator for the fields. It will not be possible to use this char in strings in the database. Similarly it will not be possible to have lineendings in the database because they mark the change between records. It's possible to overcome this by substituting the needed comma or line ending with another not often used char, like # for example. So that when showing the data on screen all # chars could be converted to line endings and the inverse when storing data back to the database. The ReplaceString routine is useful here.<br />
<br />
<syntaxhighlight><br />
uses sdfdata, db;<br />
<br />
constructor TComponentsDatabase.Create;<br />
var<br />
FDataset: TSdfDataset;<br />
begin<br />
inherited Create;<br />
<br />
FDataset := TSdfDataset.Create(nil);<br />
FDataset.FileName := vConfigurations.ComponentsDBFile;<br />
<br />
// Not necessary with TSdfDataset<br />
// FDataset.TableName := STR_DB_COMPONENTS_TABLE;<br />
// FDataset.PrimaryKey := STR_DB_COMPONENTS_ID;<br />
<br />
// Adds field definitions<br />
FDataset.FieldDefs.Add('ID', ftString);<br />
FDataset.FieldDefs.Add('NAMEEN', ftString);<br />
FDataset.FieldDefs.Add('NAMEPT', ftString);<br />
FDataset.FieldDefs.Add('HEIGHT', ftString);<br />
FDataset.FieldDefs.Add('WIDTH', ftString);<br />
FDataset.FieldDefs.Add('PINS', ftString);<br />
FDataset.FieldDefs.Add('DRAWINGCODE', ftString);<br />
<br />
// Necessary for TSdfDataset<br />
FDataset.Delimiter := ',';<br />
FDataset.FirstLineAsSchema := True;<br />
<br />
FDataset.Active := True;<br />
<br />
// Sets the initial record<br />
CurrentRecNo := 1;<br />
FDataset.First;<br />
end;</syntaxhighlight><br />
<br />
When using TSdfDataset directly be aware that RecNo, although it is implemented, does not work as a way to move through the dataset whether reading or writing records. The standard navigation routines like First, Next, Prior and Last work as expected, so you need to use them rather than RecNo.<br />
If you are used to using absolute record numbers to navigate around a database you can implement your own version of RecNo. Declare a global longint variable called CurrentRecNo which will hold the current RecNo value. Remember that this variable will have the same convention as RecNo, so the first record has number 1 (it is not zero-based). After activating the database initialize the database to the first record with TSdfDataset.First and set CurrentRecNo := 1<br />
<br />
<syntaxhighlight>{@@<br />
Moves to the desired record using TDataset.Next and TDataset.Prior<br />
This avoids using TDataset.RecNo which doesn't navigate reliably in any dataset.<br />
<br />
@param AID Indicates the record number. The first record has number 1<br />
}<br />
procedure TComponentsDatabase.GoToRec(AID: Integer);<br />
begin<br />
// We are before the desired record, move forward<br />
if CurrentRecNo < AID then<br />
begin<br />
while (not FDataset.EOF) and (CurrentRecNo < AID) do<br />
begin<br />
FDataset.Next;<br />
FDataset.CursorPosChanged;<br />
Inc(CurrentRecNo);<br />
end;<br />
end<br />
// We are after the desired record, move back<br />
else if CurrentRecNo > AID then<br />
begin<br />
while (CurrentRecNo >= 1) and (CurrentRecNo > AID) do<br />
begin<br />
FDataset.Prior;<br />
FDataset.CursorPosChanged;<br />
Dec(CurrentRecNo);<br />
end;<br />
end;<br />
end;</syntaxhighlight><br />
<br />
=== Using with data-aware controls ===<br />
<br />
== Lazarus and Advantage Database Server ==<br />
* Please see [[Advantage Database Server]] for details on using Advantage Database Server<br />
<br />
==See also==<br />
(Sorted alphabetically)<br />
* [[Databases]]<br />
* [[Database_field_type]]<br />
* [[Firebird in action]]<br />
* [[How to write in-memory database applications in Lazarus/FPC]]<br />
* [[Lazarus DB Faq]]<br />
* [[Lazarus Tdbf Tutorial]]<br />
* [[MS Access]]<br />
* [[multi-tier_options_with_fpc|Multi-tier options with FPC]]<br />
* [[MySQLDatabases]]<br />
* [[ODBCConn]]<br />
* [[SQLdb Tutorial1]]<br />
* [[SqlDBHowto]]<br />
* [[SQLite]]<br />
* [[tiOPF]] - a free and open source Object Persistence Framework.<br />
* [[Zeos tutorial]]<br />
<br />
==External links==<br />
<br />
* [http://pdo.sourceforge.net Pascal Data Objects] - a database API that worked for both FPC and Delphi and utilises native MySQL libraries for version 4.1 and 5.0 and Firebird SQL 1.5, and 2.0. It's inspired by PHP's PDO class.<br />
* [http://lazaruszeos.blogspot.com Zeos+SQLite Tutorial] - Good tutorial using screenshots and screencasts it explain how to use SQLite and Zeos, spanish (google translate does a good work in translating it to english)<br />
<br />
<br />
[[Category:Databases]]<br />
[[Category:Tutorials]]</div>Mario13https://wiki.freepascal.org/index.php?title=Lazarus_Database_Overview&diff=66010Lazarus Database Overview2013-02-18T19:40:45Z<p>Mario13: /* Lazarus and dBase */</p>
<hr />
<div>{{Translate}}<br />
<br />
== Overview ==<br />
<br />
This article is an overview of the which databases can work with Lazarus.<br />
<br />
Lazarus supports several databases out of the box (using e.g. the SQLDB framework), however the developer must install the required packages (client libraries) for each one. <br />
<br />
You can access the database through code or by dropping components on a form. The data-aware components represent fields and are connected by setting the DataSource property to point to a TDataSource. The Datasource represents a table and is connected to the database components (examples: ''TPSQLDatabase'', ''TSQLiteDataSet'') by setting the DataSet property. The data-aware components are located on the "Data Controls" tab. The Datasource and the database controls are located on the "Data Access" tab.<br />
<br />
== Lazarus and Interbase / Firebird ==<br />
* Please see [[Firebird_in_action|Firebird in action]] for details on various access methods, which include<br />
# Built-in SQLDB support<br />
# FBLib<br />
# IBX<br />
# PDO<br />
# Zeos<br />
<br />
For a tutorial that leads you through creating a Lazarus GUI for a Firebird database, see:<br />
* [[SQLdb Tutorial1]]<br />
<br />
<br />
== Lazarus and MySQL ==<br />
* Please see [[mysql]] for details on various access methods, which include:<br />
# Built-in SQLDB support<br />
# PDO<br />
# Zeos<br />
<br />
== Lazarus and MSSQL/Sybase ==<br />
You can connect to Microsoft SQL Server databases using<br />
# The built-in '''SQLdb''' (recent Lazarus/FPC 2.6.1+): '''TMSSQLConnection''' (MS SQL) and '''TSybaseConnection''' (Sybase ASE)<br />
## On Windows, you can download a recent 32 or 64 bit version of the FreeTDS library '''dblib.dll''' here: [ftp://ftp.freepascal.org/fpc/contrib/windows/]<br />
## Not necessary normally: By modifying FPC file '''dblib.pas''' SQLDB could use the "native" library '''ntwdblib.dll''' instead of the default FreeTDS library '''dblib.dll''' (in this case FPC needs to be recompiled).<br />
## On Linux by default it uses the FreeTDS library '''libsybdb.so''' (for example, in Debian is in package '''libsybd5''').<br />
# '''Zeos''' component '''TZConnection''' (latest CVS, see links to Zeos elsewhere on this page)<br />
## On Windows you can choose between native library '''ntwdblib.dll''' (protocol '''mssql''') or FreeTDS libraries (protocol '''FreeTDS_MsSQL-nnnn''') where nnnn is one of four variants depending on the server version. For Delphi (not Lazarus) there is also another Zeos protocol '''ado''' for MSSQL 2005 or later. Using protocols mssql or ado generates code not platform independient.<br />
## On Linux the only way is with FreeTDS protocols and libraries (you should use '''libsybdb.so''').<br />
# '''ODBC''' (MSSQL and Sybase ASE) with SQLdb '''TODBCConnection''' (see also [http://wiki.freepascal.org/ODBCConn#Connecting_to_Microsoft_SQL_Server])<br />
## On Windows it uses native ODBC Microsoft libraries (like sqlsrv32.dll for MSSQL 2000)<br />
## On Linux it uses unixODBC + FreeTDS (packages unixodbc or iodbc, and tdsodbc). Since 2012 there is also a Microsoft SQL Server ODBC Driver 1.0 for Linux which is a binary product (no open source) and provides native connectivity, but was released only for 64 bits and only for RedHat.<br />
<br />
Please see the FPC and Lazarus help files for details on using SQLDB with Sybase ASE and MSSQL Server.<br />
<br />
{{Note| In any of the above forms, you can connect using TCP/IP, e.g. on port 1433. }}<br />
<br />
If you use native Microsoft Libraries (over Windows) it could be possible to connect to remote server with Named Pipes. FreeTDS libraries do not support Named Pipes.<br />
<br />
{{Note| Lazarus 1.0 was released with FPC 2.6.0 and does not include TMSSQLConnection or TSybaseConnection. If you want these, it might be easiest to download a snapshot of the latest Lazarus built with FPC 2.6.1, optinally installing that in a directory different from your Lazarus 1.0 version. You can use --primary-config-path to set up a separate environment for the Lazarus snapshot (see [[Multiple Lazarus]]) }}<br />
<br />
== Lazarus and ODBC ==<br />
ODBC is a general database connection standard which is available on Linux, Windows and OSX. You will need an ODBC driver from your database vendor and set up an ODBC "data source" (also known as DSN).<br />
You can use the SQLDB components (TODBCConnection) to connect to an ODBC data soruce.<br />
See [[ODBCConn]] for more details and examples<br />
<br />
== Lazarus and Oracle ==<br />
* Acces methods include:<br />
# Built-in SQLDB support<br />
# Zeos<br />
<br />
== Lazarus and PostgreSQL ==<br />
* Please see [[postgres]] for details on various access methods, which include:<br />
# Built-in SQLdb support. Use component '''TPQConnection''' from palette '''SQLdb'''<br />
# Zeos. Use component '''TZConnection''' with protocol 'postgresql' from palette '''Zeos Access'''<br />
<br />
== Lazarus and SQLite ==<br />
SQLite is an embedded database; the database code can be distributed as a library (.dll/.so/.dylib) with your application to make it self-contained (comparable to Firebird embedded). SQLite is quite popular due to its relative simplicity, speed, small size and cross-platform support.<br />
<br />
Please see the [[SQLite]] page for details on various access methods, which include:<br />
# Built-in SQLDb support<br />
# Zeos<br />
# SQLitePass <br />
# TSQLite3Dataset<br />
<br />
== Lazarus and dBase ==<br />
<br />
FPC includes a simple database component that is derived from the Delphi TTable component called "TDbf" [http://tdbf.sourceforge.net/ TDbf Website]). It supports various DBase and Foxpro formats.<br />
<br />
TDbf does not accept SQL commands but you can use the dataset methods etc and you can also use regular databound controls such as the DBGrid.<br />
<br />
It doesn't require any sort of runtime database engine. However it's not the best option for large database applications.<br />
<br />
See the [[Lazarus Tdbf Tutorial|TDbf Tutorial page]] for the tutorial as well as documentation.<br />
<br />
You can use e.g. OpenOffice/LibreOffice Base to visually create/edit dbf files.<br />
<br />
When this code is run, your DVD collection table will be created. After that, all data aware components linked through the TDatasource to this component will allow easy access to the data.<br />
<br />
<br />
== Lazarus and Paradox ==<br />
<br />
Paradox was the default format for table files in Delphi and before [http://en.wikipedia.org/wiki/Paradox_%28database%29 Wikipedia].<br />
The concept is similar to DBF's, where the "database" is a folder, and each table is in a "file" inside that folder. Also, each index is a file too.<br />
To access this files from Lazarus:<br />
* '''TParadox''': Install package "lazparadox 0.0" included in the standard distribution. When you install this package, you will see a new component labeled "PDX" in the "Data Access" palette. In order to use this component you have to include "paradox" in the uses list. This component uses the [http://pxlib.sourceforge.net pdxlib library] which is availble in this site for Linux. In Debian, for example, you have to install pxlib1 from package manager.<br />
<br />
== Using TSdfDataset and TFixedDataset ==<br />
<br />
TSdfDataset and TFixedDataset are two simple datasets which offer a very simple textual storage format. These datasets are very convenient for small databases, because they are fully implemented as an object pascal unit, and thus require no external libraries, and because their textual format allows them to be easely edited with a text editor.<br />
<br />
Note: December 2012/FPC 2.7.1: SDFDataset is supposed to read/write CSV files according to RFC4180, but still has some problems with quoted fields etc. For more details, see [[CSV]]<br />
<br />
To start with this format, a initial database file should be created. The format is very simple, so use a text editor to do this.<br />
<br />
Bellow is a sample database for TSdfDataset. Note that the first line has the names of the fields and that we are using commas as separators:<br />
<br />
<pre>ID,NAMEEN,NAMEPT,HEIGHT,WIDTH,PINS,DRAWINGCODE<br />
1,resistor,resistor,1,1,1,LINE<br />
2,capacitor,capacitor,1,1,1,LINE<br />
3,transistor npn,transistor npn</pre><br />
<br />
And here is an example database for using with TFixedDataset. Each record occupies a fixed amount of space, and if the field is smaller then it, spaces should be used to fill the remaining size.<br />
<br />
<pre>Name = 15 chars; Surname = 15 chars; Tell = 10 chars; e_mail = 20 chars;<br />
Piet Pompies piet@pompies.net</pre><br />
<br />
=== Using the datasets directly ===<br />
<br />
Sometimes it is useful to create the dataset and work with it completely in code, and the following code will do exactly this. Note some peculiarities of TSdfDataset/TFixedDataset:<br />
<br />
* The lines in the database can have a maximum size of about 300. A fix is being researched.<br />
* It is necessary to add the field definitions. Some datasets are able to fill this information alone from the database file<br />
* One should set FirstLineAsSchema to true, to indicate that the first line includes the field names and positions<br />
* The Delimiter property holds the separator for the fields. It will not be possible to use this char in strings in the database. Similarly it will not be possible to have lineendings in the database because they mark the change between records. It's possible to overcome this by substituting the needed comma or line ending with another not often used char, like # for example. So that when showing the data on screen all # chars could be converted to line endings and the inverse when storing data back to the database. The ReplaceString routine is useful here.<br />
<br />
<syntaxhighlight><br />
uses sdfdata, db;<br />
<br />
constructor TComponentsDatabase.Create;<br />
var<br />
FDataset: TSdfDataset;<br />
begin<br />
inherited Create;<br />
<br />
FDataset := TSdfDataset.Create(nil);<br />
FDataset.FileName := vConfigurations.ComponentsDBFile;<br />
<br />
// Not necessary with TSdfDataset<br />
// FDataset.TableName := STR_DB_COMPONENTS_TABLE;<br />
// FDataset.PrimaryKey := STR_DB_COMPONENTS_ID;<br />
<br />
// Adds field definitions<br />
FDataset.FieldDefs.Add('ID', ftString);<br />
FDataset.FieldDefs.Add('NAMEEN', ftString);<br />
FDataset.FieldDefs.Add('NAMEPT', ftString);<br />
FDataset.FieldDefs.Add('HEIGHT', ftString);<br />
FDataset.FieldDefs.Add('WIDTH', ftString);<br />
FDataset.FieldDefs.Add('PINS', ftString);<br />
FDataset.FieldDefs.Add('DRAWINGCODE', ftString);<br />
<br />
// Necessary for TSdfDataset<br />
FDataset.Delimiter := ',';<br />
FDataset.FirstLineAsSchema := True;<br />
<br />
FDataset.Active := True;<br />
<br />
// Sets the initial record<br />
CurrentRecNo := 1;<br />
FDataset.First;<br />
end;</syntaxhighlight><br />
<br />
When using TSdfDataset directly be aware that RecNo, although it is implemented, does not work as a way to move through the dataset whether reading or writing records. The standard navigation routines like First, Next, Prior and Last work as expected, so you need to use them rather than RecNo.<br />
If you are used to using absolute record numbers to navigate around a database you can implement your own version of RecNo. Declare a global longint variable called CurrentRecNo which will hold the current RecNo value. Remember that this variable will have the same convention as RecNo, so the first record has number 1 (it is not zero-based). After activating the database initialize the database to the first record with TSdfDataset.First and set CurrentRecNo := 1<br />
<br />
<syntaxhighlight>{@@<br />
Moves to the desired record using TDataset.Next and TDataset.Prior<br />
This avoids using TDataset.RecNo which doesn't navigate reliably in any dataset.<br />
<br />
@param AID Indicates the record number. The first record has number 1<br />
}<br />
procedure TComponentsDatabase.GoToRec(AID: Integer);<br />
begin<br />
// We are before the desired record, move forward<br />
if CurrentRecNo < AID then<br />
begin<br />
while (not FDataset.EOF) and (CurrentRecNo < AID) do<br />
begin<br />
FDataset.Next;<br />
FDataset.CursorPosChanged;<br />
Inc(CurrentRecNo);<br />
end;<br />
end<br />
// We are after the desired record, move back<br />
else if CurrentRecNo > AID then<br />
begin<br />
while (CurrentRecNo >= 1) and (CurrentRecNo > AID) do<br />
begin<br />
FDataset.Prior;<br />
FDataset.CursorPosChanged;<br />
Dec(CurrentRecNo);<br />
end;<br />
end;<br />
end;</syntaxhighlight><br />
<br />
=== Using with data-aware controls ===<br />
<br />
== Lazarus and Advantage Database Server ==<br />
* Please see [[Advantage Database Server]] for details on using Advantage Database Server<br />
<br />
==See also==<br />
(Sorted alphabetically)<br />
* [[Databases]]<br />
* [[Database_field_type]]<br />
* [[Firebird in action]]<br />
* [[How to write in-memory database applications in Lazarus/FPC]]<br />
* [[Lazarus DB Faq]]<br />
* [[Lazarus Tdbf Tutorial]]<br />
* [[MS Access]]<br />
* [[multi-tier_options_with_fpc|Multi-tier options with FPC]]<br />
* [[MySQLDatabases]]<br />
* [[ODBCConn]]<br />
* [[SQLdb Tutorial1]]<br />
* [[SqlDBHowto]]<br />
* [[SQLite]]<br />
* [[tiOPF]] - a free and open source Object Persistence Framework.<br />
* [[Zeos tutorial]]<br />
<br />
==External links==<br />
<br />
* [http://pdo.sourceforge.net Pascal Data Objects] - a database API that worked for both FPC and Delphi and utilises native MySQL libraries for version 4.1 and 5.0 and Firebird SQL 1.5, and 2.0. It's inspired by PHP's PDO class.<br />
* [http://lazaruszeos.blogspot.com Zeos+SQLite Tutorial] - Good tutorial using screenshots and screencasts it explain how to use SQLite and Zeos, spanish (google translate does a good work in translating it to english)<br />
<br />
<br />
[[Category:Databases]]<br />
[[Category:Tutorials]]</div>Mario13https://wiki.freepascal.org/index.php?title=Lazarus_Database_Overview&diff=62561Lazarus Database Overview2012-10-08T18:56:53Z<p>Mario13: /* Lazarus and MSSQL/Sybase */</p>
<hr />
<div>{{Translate}}<br />
<br />
== Overview ==<br />
<br />
This article is an overview of the which databases can work with Lazarus.<br />
<br />
Lazarus supports several databases out of the box (using e.g. the SQLDB framework), however the developer must install the required packages (client libraries) for each one. <br />
<br />
You can access the database through code or by dropping components on a form. The data-aware components represent fields and are connected by setting the DataSource property to point to a TDataSource. The Datasource represents a table and is connected to the database components (examples: ''TPSQLDatabase'', ''TSQLiteDataSet'') by setting the DataSet property. The data-aware components are located on the "Data Controls" tab. The Datasource and the database controls are located on the "Data Access" tab.<br />
<br />
== Lazarus and Interbase / Firebird ==<br />
* Please see [[Firebird_in_action|Firebird in action]] for details on various access methods, which include<br />
# Built-in SQLDB support<br />
# FBLib<br />
# IBX<br />
# PDO<br />
# Zeos<br />
<br />
For a tutorial that leads you through creating a Lazarus GUI for a Firebird database, see:<br />
* [[SQLdb Tutorial1]]<br />
<br />
<br />
== Lazarus and MySQL ==<br />
* Please see [[mysql]] for details on various access methods, which include:<br />
# Built-in SQLDB support<br />
# PDO<br />
# Zeos<br />
<br />
== Lazarus and MSSQL/Sybase ==<br />
You can connect to Microsoft SQL Server databases using<br />
# The built-in '''SQLdb''' (recent Lazarus/FPC 2.6.1+): '''TMSSQLConnection''' (MS SQL) and '''TSybaseConnection''' (Sybase ASE)<br />
## On Windows by default it use FreeTDS library '''dblib.dll'''. By modifying FPC file '''dblib.pas''' it could use native library ntwdblib.dll (in this case FPC needs to be recompiled).<br />
## On Linux by default it use '''libsybdb.so''' which is FreeTDS library (for example, in Debian is in package '''libsybd5''').<br />
# '''Zeos''' component '''TZConnection''' (latest CVS, see links to Zeos elsewhere on this page)<br />
## On Windows you can choose between native library ntwdblib.dll (protocol '''mssql''') or FreeTDS libraries (protocol '''FreeTDS_MsSQL-nnnn''') where nnnn is one of four variants depending on the server version. For Delphi (not Lazarus) there is also another Zeos protocol '''ado''' for MSSQL 2005 or later. Using protocols mssql or ado generates code not platform independient.<br />
## On Linux the only way is with FreeTDS protocols and libraries (you should use '''libsybdb.so''').<br />
# '''ODBC''' (MSSQL and Sybase ASE) with SQLdb '''TODBCConnection''' (see also [http://wiki.freepascal.org/ODBCConn#Connecting_to_Microsoft_SQL_Server])<br />
## On Windows it uses native ODBC Microsoft libraries (like sqlsrv32.dll for MSSQL 2000)<br />
## On Linux it uses unixODBC + FreeTDS (packages unixodbc or iodbc, and tdsodbc). Since 2012 there is also a Microsoft SQL Server ODBC Driver 1.0 for Linux which is a binary product (no open source) and provides native connectivity, but was released only for 64 bits and only for RedHat.<br />
<br />
Please see the FPC and Lazarus help files for details on using SQLDB with Sybase ASE and MSSQL Server.<br />
<br />
Note1: In any of the above forms, if you use native Microsoft Libraries (over Windows) it could be possible to connect to remote server with Named Pipes or with TCP/IP with fixed port (like 1433). If you use Wine in Linux only FreeTDS libraries are working, native libraries or Named Pipes will not work in Wine. On the other hand, if you use FreeTDS libraries (in Windows or Linux), connecting with Named Pipes is not supported by FreeTDS, only TCP/IP connections with fixed port (like 1433) are supported.<br />
<br />
Note2: Lazarus 1.0 was released with FPC 2.6.0 and does not include TMSSQLConnection or TSybaseConnection. If you want these, it might be easiest to download a snapshot of the latest Lazarus built with FPC 2.6.1, optinally installing that in a directory different from your Lazarus 1.0 version. You can use --primary-config-path to set up a separate environment for the Lazarus snapshot (see [[Multiple_Lazarus]])<br />
<br />
== Lazarus and ODBC ==<br />
ODBC is a general database connection standard which is available on Linux, Windows and OSX. You will need an ODBC driver from your database vendor and set up an ODBC "data source" (also known as DSN).<br />
You can use the SQLDB components (TODBCConnection) to connect to an ODBC data soruce.<br />
See [[ODBCConn]] for more details and examples<br />
<br />
== Lazarus and Oracle ==<br />
* Acces methods include:<br />
# Built-in SQLDB support<br />
# Zeos<br />
<br />
== Lazarus and PostgreSQL ==<br />
* Please see [[postgres]] for details on various access methods, which include:<br />
# Built-in SQLdb support. Use component '''TPQConnection''' from palette '''SQLdb'''<br />
# Zeos. Use component '''TZConnection''' with protocol 'postgresql' from palette '''Zeos Access'''<br />
<br />
== Lazarus and SQLite ==<br />
SQLite is an embedded database; the database code can be distributed as a library (.dll/.so/.dylib) with your application to make it self-contained (comparable to Firebird embedded). SQLite is quite popular due to its relative simplicity, speed, small size and cross-platform support.<br />
<br />
Please see the [[SQLite]] page for details on various access methods, which include:<br />
# Built-in SQLDb support<br />
# Zeos<br />
# SQLitePass <br />
# TSQLite3Dataset<br />
<br />
== Lazarus and dBase ==<br />
<br />
[[user:Tonymaro|Tony Maro]]<br />
<br />
You might also want to visit the [[Lazarus Tdbf Tutorial|TDbf Tutorial page]]<br />
<br />
FPC includes a simple database component that is similar in function to the Delphi TTable component called "TDbf" ([http://tdbf.sourceforge.net/ TDbf Website]) that supports a subset of features for dBase files. It is not installed by default, so you will first need to install the Lazarus package from the "lazarus/components/tdbf" directory and rebuild your Lazarus IDE. It will then appear next to the TDatasource in your component palette (Data Access tab).<br />
<br />
The TDbf component has an advantage over other database components in that it doesn't require any sort of runtime database engine. However it's not the best option for large database applications.<br />
<br />
It's very easy to use. Simply drop a TDbf on your form, set the runtime path to the directory that your database files will be in, set the table name, and link it to your TDatasource component.<br />
<br />
Real functionality requires a bit more effort, however. If a table doesn't already exist, you'll need to create it programmatically, unless there's a compatible table designer I'm not familiar with.<br />
Note: Current version of OpenOffice/LibreOffice (3.x) contains OpenOffice Base, which can create dbf files in a somewhat user-friendly way.<br />
<br />
Attempting to open a nonexistent table will generate an error. Tables can be created programmatically through the component after the runtime path and table name are set.<br />
<br />
For instance, to create a table called "dvds" to store your DVD collection you would drop it on your form, set the runtime path, and set the table name to "dvds". The resulting file will be called "dvds.dbf".<br />
<br />
In your code, insert the following:<br />
<br />
<syntaxhighlight>Dbf1.FilePathFull := '/path/to/my/database';<br />
Dbf1.TableName := 'dvds';<br />
With Dbf1.FieldDefs do begin<br />
Add('Name', ftString, 80, True);<br />
Add('Description', ftMemo, 0, False);<br />
Add('Rating', ftString, 5, False);<br />
end;<br />
Dbf1.CreateTable;</syntaxhighlight><br />
<br />
When this code is run, your DVD collection table will be created. After that, all data aware components linked through the TDatasource to this component will allow easy access to the data. <br />
<br />
Adding an index is a little different from your typical TTable. It must be done after the database is open. You use the same method also to rebuild the indices. For instance:<br />
<br />
<syntaxhighlight>Dbf1.Exclusive := True;<br />
Dbf1.Open;<br />
Dbf1.AddIndex('dvdsname','Name',[ixPrimary, ixUnique, ixCaseInsensitive]);<br />
Dbf1.AddIndex('rating.ndx', 'Rating', [ixCaseInsensitive]);<br />
Dbf1.Close;</syntaxhighlight><br />
<br />
The first (primary) index will be a file called "dvdsname.mdx" and the second will be a file named "rating.ndx" so in a multiple table database you must be careful not to use the same file name again.<br />
<br />
Please see [[Lazarus Tdbf Tutorial|TDbf Tutorial page]] for more details, but hopefully this will get those old Delphi programmers up and running with databases in Lazarus!<br />
<br />
===Searching and Displaying a data set===<br />
<br />
[[user:svbfieldview.net|Simon Batty]]<br />
<br />
In this example I wanted to search a database of books for all the titles an author has listed<br />
and then display the list in a memo box<br />
<syntaxhighlight>Dbf1.FilePathFull := '/home/somelocatio/database_location/'; // path to the database directory<br />
Dbf1.TableName := 'books.dbase'; // database file (including extension)<br />
DbF1.Open;<br />
memo1.Clear; // clear the memo box<br />
<br />
Dbf1.FilterOptions := [foCaseInsensitive];<br />
Df1.Filter := 'AU=' + QuotedStr('anauthor'); // AU is the field name containing the authors<br />
<br />
Dbf1.Filtered := true; // This selects the filtered set<br />
Dbf1.First; // moves the the first filtered data<br />
while not dbf1.EOF do // prints the titles that match the author to the memo box<br />
begin<br />
memo1.Append(Dbf1.FieldByName('TI').AsString); // TI is the field name for titles<br />
dbf1.next; // use .next here NOT .findnext!<br />
end;<br />
Dbf1.Close;</syntaxhighlight> <br />
<br />
Note that you can use Ddf1.findfirst to get the first record in the filtered set, then use <br />
Dbf1.next to move though the data. I found that using Dbf1.Findnext just causes the program to hang. <br />
<br />
This database was generated using TurboBD that came with the Kylix 1. I cannot get TurboBD tables to work with Lazarus, however you can download a command line tool from TurboDB's website that allows you to convert TurboDB table to other formats.<br />
<br />
== Using TSdfDataset and TFixedDataset ==<br />
<br />
TSdfDataset and TFixedDataset are two simple datasets which offer a very simple textual storage format. These datasets are very convenient for small databases, because they are fully implemented as an object pascal unit, and thus require no external libraries, and because their textual format allows them to be easely edited with a text editor.<br />
<br />
To start with this formats, a initial database file should be created. The format is very simple, so use a text editor to do this.<br />
<br />
Bellow is a sample database for TSdfDataset. Note that the first line has the names of the fields and that we are using commas as separators:<br />
<br />
<pre>ID,NAMEEN,NAMEPT,HEIGHT,WIDTH,PINS,DRAWINGCODE<br />
1,resistor,resistor,1,1,1,LINE<br />
2,capacitor,capacitor,1,1,1,LINE<br />
3,transistor npn,transistor npn</pre><br />
<br />
And here is an example database for using with TFixedDataset. Each record occupies a fixed amount of space, and if the field is smaller then it, spaces should be used to fill the remaining size.<br />
<br />
<pre>Name = 15 chars; Surname = 15 chars; Tell = 10 chars; e_mail = 20 chars;<br />
Piet Pompies piet@pompies.net</pre><br />
<br />
=== Using the datasets directly ===<br />
<br />
Sometimes it is useful to create the dataset and work with it completely in code, and the following code will do exactly this. Note some peculiarities of TSdfDataset/TFixedDataset:<br />
<br />
* The lines in the database can have a maximum size of about 300. A fix is being researched.<br />
* It is necessary to add the field definitions. Some datasets are able to fill this information alone from the database file<br />
* One should set FirstLineAsSchema to true, to indicate that the first line includes the field names and positions<br />
* The Delimiter property holds the separator for the fields. It will not be possible to use this char in strings in the database. Similarly it will not be possible to have lineendings in the database because they mark the change between records. It's possible to overcome this by substituting the needed comma or line ending with another not often used char, like # for example. So that when showing the data on screen all # chars could be converted to line endings and the inverse when storing data back to the database. The ReplaceString routine is useful here.<br />
<br />
<syntaxhighlight><br />
uses sdfdata, db;<br />
<br />
constructor TComponentsDatabase.Create;<br />
var<br />
FDataset: TSdfDataset;<br />
begin<br />
inherited Create;<br />
<br />
FDataset := TSdfDataset.Create(nil);<br />
FDataset.FileName := vConfigurations.ComponentsDBFile;<br />
<br />
// Not necessary with TSdfDataset<br />
// FDataset.TableName := STR_DB_COMPONENTS_TABLE;<br />
// FDataset.PrimaryKey := STR_DB_COMPONENTS_ID;<br />
<br />
// Adds field definitions<br />
FDataset.FieldDefs.Add('ID', ftString);<br />
FDataset.FieldDefs.Add('NAMEEN', ftString);<br />
FDataset.FieldDefs.Add('NAMEPT', ftString);<br />
FDataset.FieldDefs.Add('HEIGHT', ftString);<br />
FDataset.FieldDefs.Add('WIDTH', ftString);<br />
FDataset.FieldDefs.Add('PINS', ftString);<br />
FDataset.FieldDefs.Add('DRAWINGCODE', ftString);<br />
<br />
// Necessary for TSdfDataset<br />
FDataset.Delimiter := ',';<br />
FDataset.FirstLineAsSchema := True;<br />
<br />
FDataset.Active := True;<br />
<br />
// Sets the initial record<br />
CurrentRecNo := 1;<br />
FDataset.First;<br />
end;</syntaxhighlight><br />
<br />
When using TSdfDataset directly be aware that RecNo, although it is implemented, does not work as a way to move through the dataset whether reading or writing records. The standard navigation routines like First, Next, Prior and Last work as expected, so you need to use them rather than RecNo.<br />
If you are used to using absolute record numbers to navigate around a database you can implement your own version of RecNo. Declare a global longint variable called CurrentRecNo which will hold the current RecNo value. Remember that this variable will have the same convention as RecNo, so the first record has number 1 (it is not zero-based). After activating the database initialize the database to the first record with TSdfDataset.First and set CurrentRecNo := 1<br />
<br />
<syntaxhighlight>{@@<br />
Moves to the desired record using TDataset.Next and TDataset.Prior<br />
This avoids using TDataset.RecNo which doesn't navigate reliably in any dataset.<br />
<br />
@param AID Indicates the record number. The first record has number 1<br />
}<br />
procedure TComponentsDatabase.GoToRec(AID: Integer);<br />
begin<br />
// We are before the desired record, move forward<br />
if CurrentRecNo < AID then<br />
begin<br />
while (not FDataset.EOF) and (CurrentRecNo < AID) do<br />
begin<br />
FDataset.Next;<br />
FDataset.CursorPosChanged;<br />
Inc(CurrentRecNo);<br />
end;<br />
end<br />
// We are after the desired record, move back<br />
else if CurrentRecNo > AID then<br />
begin<br />
while (CurrentRecNo >= 1) and (CurrentRecNo > AID) do<br />
begin<br />
FDataset.Prior;<br />
FDataset.CursorPosChanged;<br />
Dec(CurrentRecNo);<br />
end;<br />
end;<br />
end;</syntaxhighlight><br />
<br />
=== Using with data-aware controls ===<br />
<br />
== Lazarus and Advantage Database Server ==<br />
* Please see [[Advantage Database Server]] for details on using Advantage Database Server<br />
<br />
==See also==<br />
* [[Database_field_type]]<br />
* [[Databases]]<br />
* [[Databases in Lazarus]]<br />
* [[Firebird in action]]<br />
* [[How to write in-memory database applications in Lazarus/FPC]]<br />
* [[Lazarus DB Faq]]<br />
* [[Lazarus Tdbf Tutorial]]<br />
* [[MS Access]]<br />
* [[multi-tier_options_with_fpc|Multi-tier options with FPC]]<br />
* [[MySQLDatabases]]<br />
* [[ODBCConn]]<br />
* [[SQLdb Tutorial1]]<br />
* [[SqlDBHowto]]<br />
* [[SQLite]]<br />
* [[tiOPF]] - a free and open source Object Persistence Framework.<br />
* [[Zeos tutorial]]<br />
<br />
==External links==<br />
<br />
* [http://pdo.sourceforge.net Pascal Data Objects] - a database API that worked for both FPC and Delphi and utilises native MySQL libraries for version 4.1 and 5.0 and Firebird SQL 1.5, and 2.0. It's inspired by PHP's PDO class.<br />
* [http://lazaruszeos.blogspot.com Zeos+SQLite Tutorial] - Good tutorial using screenshots and screencasts it explain how to use SQLite and Zeos, spanish (google translate does a good work in translating it to english)<br />
<br />
<br />
[[Category:Databases]]<br />
[[Category:Tutorials]]</div>Mario13https://wiki.freepascal.org/index.php?title=Lazarus_Database_Overview&diff=62560Lazarus Database Overview2012-10-08T18:55:19Z<p>Mario13: /* Lazarus and MSSQL/Sybase */</p>
<hr />
<div>{{Translate}}<br />
<br />
== Overview ==<br />
<br />
This article is an overview of the which databases can work with Lazarus.<br />
<br />
Lazarus supports several databases out of the box (using e.g. the SQLDB framework), however the developer must install the required packages (client libraries) for each one. <br />
<br />
You can access the database through code or by dropping components on a form. The data-aware components represent fields and are connected by setting the DataSource property to point to a TDataSource. The Datasource represents a table and is connected to the database components (examples: ''TPSQLDatabase'', ''TSQLiteDataSet'') by setting the DataSet property. The data-aware components are located on the "Data Controls" tab. The Datasource and the database controls are located on the "Data Access" tab.<br />
<br />
== Lazarus and Interbase / Firebird ==<br />
* Please see [[Firebird_in_action|Firebird in action]] for details on various access methods, which include<br />
# Built-in SQLDB support<br />
# FBLib<br />
# IBX<br />
# PDO<br />
# Zeos<br />
<br />
For a tutorial that leads you through creating a Lazarus GUI for a Firebird database, see:<br />
* [[SQLdb Tutorial1]]<br />
<br />
<br />
== Lazarus and MySQL ==<br />
* Please see [[mysql]] for details on various access methods, which include:<br />
# Built-in SQLDB support<br />
# PDO<br />
# Zeos<br />
<br />
== Lazarus and MSSQL/Sybase ==<br />
You can connect to Microsoft SQL Server databases using<br />
# The built-in '''SQLdb''' (recent Lazarus/FPC 2.6.1+): '''TMSSQLConnection''' (MS SQL) and '''TSybaseConnection''' (Sybase ASE)<br />
## On Windows by default it use FreeTDS library '''dblib.dll'''. By modifying FPC file '''dblib.pas''' it could use native library ntwdblib.dll (in this case FPC needs to be recompiled).<br />
## On Linux by default it use '''libsybdb.so''' which is FreeTDS library (for example, in Debian is in package '''libsybd5''').<br />
# '''Zeos''' component '''TZConnection''' (latest CVS, see links to Zeos elsewhere on this page)<br />
## On Windows you can choose between native library ntwdblib.dll (protocol '''mssql''') or FreeTDS libraries (protocol '''FreeTDS_MsSQL-nnnn''') where nnnn is one of four variants depending on the server version. For Delphi (not Lazarus) there is also another Zeos protocol '''ado''' for MSSQL 2005 or later. Using protocols mssql or ado generates code not platform independient.<br />
## On Linux the only way is with FreeTDS protocols and libraries (you should use '''libsybdb.so''').<br />
# '''ODBC''' (MSSQL and Sybase ASE) with SQLdb '''TODBCConnection''' (see also [ODBCConn#Connecting_to_Microsoft_SQL_Server some examples])<br />
## On Windows it uses native ODBC Microsoft libraries (like sqlsrv32.dll for MSSQL 2000)<br />
## On Linux it uses unixODBC + FreeTDS (packages unixodbc or iodbc, and tdsodbc). Since 2012 there is also a Microsoft SQL Server ODBC Driver 1.0 for Linux which is a binary product (no open source) and provides native connectivity, but was released only for 64 bits and only for RedHat.<br />
<br />
Please see the FPC and Lazarus help files for details on using SQLDB with Sybase ASE and MSSQL Server.<br />
<br />
Note1: In any of the above forms, if you use native Microsoft Libraries (over Windows) it could be possible to connect to remote server with Named Pipes or with TCP/IP with fixed port (like 1433). If you use Wine in Linux only FreeTDS libraries are working, native libraries or Named Pipes will not work in Wine. On the other hand, if you use FreeTDS libraries (in Windows or Linux), connecting with Named Pipes is not supported by FreeTDS, only TCP/IP connections with fixed port (like 1433) are supported.<br />
<br />
Note2: Lazarus 1.0 was released with FPC 2.6.0 and does not include TMSSQLConnection or TSybaseConnection. If you want these, it might be easiest to download a snapshot of the latest Lazarus built with FPC 2.6.1, optinally installing that in a directory different from your Lazarus 1.0 version. You can use --primary-config-path to set up a separate environment for the Lazarus snapshot (see [[Multiple_Lazarus]])<br />
<br />
== Lazarus and ODBC ==<br />
ODBC is a general database connection standard which is available on Linux, Windows and OSX. You will need an ODBC driver from your database vendor and set up an ODBC "data source" (also known as DSN).<br />
You can use the SQLDB components (TODBCConnection) to connect to an ODBC data soruce.<br />
See [[ODBCConn]] for more details and examples<br />
<br />
== Lazarus and Oracle ==<br />
* Acces methods include:<br />
# Built-in SQLDB support<br />
# Zeos<br />
<br />
== Lazarus and PostgreSQL ==<br />
* Please see [[postgres]] for details on various access methods, which include:<br />
# Built-in SQLdb support. Use component '''TPQConnection''' from palette '''SQLdb'''<br />
# Zeos. Use component '''TZConnection''' with protocol 'postgresql' from palette '''Zeos Access'''<br />
<br />
== Lazarus and SQLite ==<br />
SQLite is an embedded database; the database code can be distributed as a library (.dll/.so/.dylib) with your application to make it self-contained (comparable to Firebird embedded). SQLite is quite popular due to its relative simplicity, speed, small size and cross-platform support.<br />
<br />
Please see the [[SQLite]] page for details on various access methods, which include:<br />
# Built-in SQLDb support<br />
# Zeos<br />
# SQLitePass <br />
# TSQLite3Dataset<br />
<br />
== Lazarus and dBase ==<br />
<br />
[[user:Tonymaro|Tony Maro]]<br />
<br />
You might also want to visit the [[Lazarus Tdbf Tutorial|TDbf Tutorial page]]<br />
<br />
FPC includes a simple database component that is similar in function to the Delphi TTable component called "TDbf" ([http://tdbf.sourceforge.net/ TDbf Website]) that supports a subset of features for dBase files. It is not installed by default, so you will first need to install the Lazarus package from the "lazarus/components/tdbf" directory and rebuild your Lazarus IDE. It will then appear next to the TDatasource in your component palette (Data Access tab).<br />
<br />
The TDbf component has an advantage over other database components in that it doesn't require any sort of runtime database engine. However it's not the best option for large database applications.<br />
<br />
It's very easy to use. Simply drop a TDbf on your form, set the runtime path to the directory that your database files will be in, set the table name, and link it to your TDatasource component.<br />
<br />
Real functionality requires a bit more effort, however. If a table doesn't already exist, you'll need to create it programmatically, unless there's a compatible table designer I'm not familiar with.<br />
Note: Current version of OpenOffice/LibreOffice (3.x) contains OpenOffice Base, which can create dbf files in a somewhat user-friendly way.<br />
<br />
Attempting to open a nonexistent table will generate an error. Tables can be created programmatically through the component after the runtime path and table name are set.<br />
<br />
For instance, to create a table called "dvds" to store your DVD collection you would drop it on your form, set the runtime path, and set the table name to "dvds". The resulting file will be called "dvds.dbf".<br />
<br />
In your code, insert the following:<br />
<br />
<syntaxhighlight>Dbf1.FilePathFull := '/path/to/my/database';<br />
Dbf1.TableName := 'dvds';<br />
With Dbf1.FieldDefs do begin<br />
Add('Name', ftString, 80, True);<br />
Add('Description', ftMemo, 0, False);<br />
Add('Rating', ftString, 5, False);<br />
end;<br />
Dbf1.CreateTable;</syntaxhighlight><br />
<br />
When this code is run, your DVD collection table will be created. After that, all data aware components linked through the TDatasource to this component will allow easy access to the data. <br />
<br />
Adding an index is a little different from your typical TTable. It must be done after the database is open. You use the same method also to rebuild the indices. For instance:<br />
<br />
<syntaxhighlight>Dbf1.Exclusive := True;<br />
Dbf1.Open;<br />
Dbf1.AddIndex('dvdsname','Name',[ixPrimary, ixUnique, ixCaseInsensitive]);<br />
Dbf1.AddIndex('rating.ndx', 'Rating', [ixCaseInsensitive]);<br />
Dbf1.Close;</syntaxhighlight><br />
<br />
The first (primary) index will be a file called "dvdsname.mdx" and the second will be a file named "rating.ndx" so in a multiple table database you must be careful not to use the same file name again.<br />
<br />
Please see [[Lazarus Tdbf Tutorial|TDbf Tutorial page]] for more details, but hopefully this will get those old Delphi programmers up and running with databases in Lazarus!<br />
<br />
===Searching and Displaying a data set===<br />
<br />
[[user:svbfieldview.net|Simon Batty]]<br />
<br />
In this example I wanted to search a database of books for all the titles an author has listed<br />
and then display the list in a memo box<br />
<syntaxhighlight>Dbf1.FilePathFull := '/home/somelocatio/database_location/'; // path to the database directory<br />
Dbf1.TableName := 'books.dbase'; // database file (including extension)<br />
DbF1.Open;<br />
memo1.Clear; // clear the memo box<br />
<br />
Dbf1.FilterOptions := [foCaseInsensitive];<br />
Df1.Filter := 'AU=' + QuotedStr('anauthor'); // AU is the field name containing the authors<br />
<br />
Dbf1.Filtered := true; // This selects the filtered set<br />
Dbf1.First; // moves the the first filtered data<br />
while not dbf1.EOF do // prints the titles that match the author to the memo box<br />
begin<br />
memo1.Append(Dbf1.FieldByName('TI').AsString); // TI is the field name for titles<br />
dbf1.next; // use .next here NOT .findnext!<br />
end;<br />
Dbf1.Close;</syntaxhighlight> <br />
<br />
Note that you can use Ddf1.findfirst to get the first record in the filtered set, then use <br />
Dbf1.next to move though the data. I found that using Dbf1.Findnext just causes the program to hang. <br />
<br />
This database was generated using TurboBD that came with the Kylix 1. I cannot get TurboBD tables to work with Lazarus, however you can download a command line tool from TurboDB's website that allows you to convert TurboDB table to other formats.<br />
<br />
== Using TSdfDataset and TFixedDataset ==<br />
<br />
TSdfDataset and TFixedDataset are two simple datasets which offer a very simple textual storage format. These datasets are very convenient for small databases, because they are fully implemented as an object pascal unit, and thus require no external libraries, and because their textual format allows them to be easely edited with a text editor.<br />
<br />
To start with this formats, a initial database file should be created. The format is very simple, so use a text editor to do this.<br />
<br />
Bellow is a sample database for TSdfDataset. Note that the first line has the names of the fields and that we are using commas as separators:<br />
<br />
<pre>ID,NAMEEN,NAMEPT,HEIGHT,WIDTH,PINS,DRAWINGCODE<br />
1,resistor,resistor,1,1,1,LINE<br />
2,capacitor,capacitor,1,1,1,LINE<br />
3,transistor npn,transistor npn</pre><br />
<br />
And here is an example database for using with TFixedDataset. Each record occupies a fixed amount of space, and if the field is smaller then it, spaces should be used to fill the remaining size.<br />
<br />
<pre>Name = 15 chars; Surname = 15 chars; Tell = 10 chars; e_mail = 20 chars;<br />
Piet Pompies piet@pompies.net</pre><br />
<br />
=== Using the datasets directly ===<br />
<br />
Sometimes it is useful to create the dataset and work with it completely in code, and the following code will do exactly this. Note some peculiarities of TSdfDataset/TFixedDataset:<br />
<br />
* The lines in the database can have a maximum size of about 300. A fix is being researched.<br />
* It is necessary to add the field definitions. Some datasets are able to fill this information alone from the database file<br />
* One should set FirstLineAsSchema to true, to indicate that the first line includes the field names and positions<br />
* The Delimiter property holds the separator for the fields. It will not be possible to use this char in strings in the database. Similarly it will not be possible to have lineendings in the database because they mark the change between records. It's possible to overcome this by substituting the needed comma or line ending with another not often used char, like # for example. So that when showing the data on screen all # chars could be converted to line endings and the inverse when storing data back to the database. The ReplaceString routine is useful here.<br />
<br />
<syntaxhighlight><br />
uses sdfdata, db;<br />
<br />
constructor TComponentsDatabase.Create;<br />
var<br />
FDataset: TSdfDataset;<br />
begin<br />
inherited Create;<br />
<br />
FDataset := TSdfDataset.Create(nil);<br />
FDataset.FileName := vConfigurations.ComponentsDBFile;<br />
<br />
// Not necessary with TSdfDataset<br />
// FDataset.TableName := STR_DB_COMPONENTS_TABLE;<br />
// FDataset.PrimaryKey := STR_DB_COMPONENTS_ID;<br />
<br />
// Adds field definitions<br />
FDataset.FieldDefs.Add('ID', ftString);<br />
FDataset.FieldDefs.Add('NAMEEN', ftString);<br />
FDataset.FieldDefs.Add('NAMEPT', ftString);<br />
FDataset.FieldDefs.Add('HEIGHT', ftString);<br />
FDataset.FieldDefs.Add('WIDTH', ftString);<br />
FDataset.FieldDefs.Add('PINS', ftString);<br />
FDataset.FieldDefs.Add('DRAWINGCODE', ftString);<br />
<br />
// Necessary for TSdfDataset<br />
FDataset.Delimiter := ',';<br />
FDataset.FirstLineAsSchema := True;<br />
<br />
FDataset.Active := True;<br />
<br />
// Sets the initial record<br />
CurrentRecNo := 1;<br />
FDataset.First;<br />
end;</syntaxhighlight><br />
<br />
When using TSdfDataset directly be aware that RecNo, although it is implemented, does not work as a way to move through the dataset whether reading or writing records. The standard navigation routines like First, Next, Prior and Last work as expected, so you need to use them rather than RecNo.<br />
If you are used to using absolute record numbers to navigate around a database you can implement your own version of RecNo. Declare a global longint variable called CurrentRecNo which will hold the current RecNo value. Remember that this variable will have the same convention as RecNo, so the first record has number 1 (it is not zero-based). After activating the database initialize the database to the first record with TSdfDataset.First and set CurrentRecNo := 1<br />
<br />
<syntaxhighlight>{@@<br />
Moves to the desired record using TDataset.Next and TDataset.Prior<br />
This avoids using TDataset.RecNo which doesn't navigate reliably in any dataset.<br />
<br />
@param AID Indicates the record number. The first record has number 1<br />
}<br />
procedure TComponentsDatabase.GoToRec(AID: Integer);<br />
begin<br />
// We are before the desired record, move forward<br />
if CurrentRecNo < AID then<br />
begin<br />
while (not FDataset.EOF) and (CurrentRecNo < AID) do<br />
begin<br />
FDataset.Next;<br />
FDataset.CursorPosChanged;<br />
Inc(CurrentRecNo);<br />
end;<br />
end<br />
// We are after the desired record, move back<br />
else if CurrentRecNo > AID then<br />
begin<br />
while (CurrentRecNo >= 1) and (CurrentRecNo > AID) do<br />
begin<br />
FDataset.Prior;<br />
FDataset.CursorPosChanged;<br />
Dec(CurrentRecNo);<br />
end;<br />
end;<br />
end;</syntaxhighlight><br />
<br />
=== Using with data-aware controls ===<br />
<br />
== Lazarus and Advantage Database Server ==<br />
* Please see [[Advantage Database Server]] for details on using Advantage Database Server<br />
<br />
==See also==<br />
* [[Database_field_type]]<br />
* [[Databases]]<br />
* [[Databases in Lazarus]]<br />
* [[Firebird in action]]<br />
* [[How to write in-memory database applications in Lazarus/FPC]]<br />
* [[Lazarus DB Faq]]<br />
* [[Lazarus Tdbf Tutorial]]<br />
* [[MS Access]]<br />
* [[multi-tier_options_with_fpc|Multi-tier options with FPC]]<br />
* [[MySQLDatabases]]<br />
* [[ODBCConn]]<br />
* [[SQLdb Tutorial1]]<br />
* [[SqlDBHowto]]<br />
* [[SQLite]]<br />
* [[tiOPF]] - a free and open source Object Persistence Framework.<br />
* [[Zeos tutorial]]<br />
<br />
==External links==<br />
<br />
* [http://pdo.sourceforge.net Pascal Data Objects] - a database API that worked for both FPC and Delphi and utilises native MySQL libraries for version 4.1 and 5.0 and Firebird SQL 1.5, and 2.0. It's inspired by PHP's PDO class.<br />
* [http://lazaruszeos.blogspot.com Zeos+SQLite Tutorial] - Good tutorial using screenshots and screencasts it explain how to use SQLite and Zeos, spanish (google translate does a good work in translating it to english)<br />
<br />
<br />
[[Category:Databases]]<br />
[[Category:Tutorials]]</div>Mario13https://wiki.freepascal.org/index.php?title=Lazarus_Database_Overview&diff=62559Lazarus Database Overview2012-10-08T18:43:53Z<p>Mario13: /* Lazarus and MSSQL/Sybase */</p>
<hr />
<div>{{Translate}}<br />
<br />
== Overview ==<br />
<br />
This article is an overview of the which databases can work with Lazarus.<br />
<br />
Lazarus supports several databases out of the box (using e.g. the SQLDB framework), however the developer must install the required packages (client libraries) for each one. <br />
<br />
You can access the database through code or by dropping components on a form. The data-aware components represent fields and are connected by setting the DataSource property to point to a TDataSource. The Datasource represents a table and is connected to the database components (examples: ''TPSQLDatabase'', ''TSQLiteDataSet'') by setting the DataSet property. The data-aware components are located on the "Data Controls" tab. The Datasource and the database controls are located on the "Data Access" tab.<br />
<br />
== Lazarus and Interbase / Firebird ==<br />
* Please see [[Firebird_in_action|Firebird in action]] for details on various access methods, which include<br />
# Built-in SQLDB support<br />
# FBLib<br />
# IBX<br />
# PDO<br />
# Zeos<br />
<br />
For a tutorial that leads you through creating a Lazarus GUI for a Firebird database, see:<br />
* [[SQLdb Tutorial1]]<br />
<br />
<br />
== Lazarus and MySQL ==<br />
* Please see [[mysql]] for details on various access methods, which include:<br />
# Built-in SQLDB support<br />
# PDO<br />
# Zeos<br />
<br />
== Lazarus and MSSQL/Sybase ==<br />
You can connect to Microsoft SQL Server databases using<br />
# The built-in '''SQLdb''' (recent Lazarus/FPC 2.6.1+): '''TMSSQLConnection''' (MS SQL) and '''TSybaseConnection''' (Sybase ASE)<br />
## On Windows by default it use FreeTDS library '''dblib.dll'''. By modifying FPC file '''dblib.pas''' it could use native library ntwdblib.dll (in this case FPC needs to be recompiled).<br />
## On Linux by default it use '''libsybdb.so''' which is FreeTDS library (for example, in Debian is in package '''libsybd5''').<br />
# '''Zeos''' component '''TZConnection''' (latest CVS, see links to Zeos elsewhere on this page)<br />
## On Windows you can choose between native library ntwdblib.dll (protocol '''mssql''') or FreeTDS libraries (protocol '''FreeTDS_MsSQL-nnnn''') where nnnn is one of four variants depending on the server version. For Delphi (not Lazarus) there is also another Zeos protocol '''ado''' for MSSQL 2005 or later. Using protocols mssql or ado generates code not platform independient.<br />
## On Linux the only way is with FreeTDS protocols and libraries (you should use '''libsybdb.so''').<br />
# '''ODBC''' (MSSQL and Sybase ASE) with SQLdb '''TODBCConnection''' (see also [http://wiki.freepascal.org/ODBCConn#Connecting_to_Microsoft_SQL_Server])<br />
## On Windows it uses native ODBC Microsoft libraries (like sqlsrv32.dll for MSSQL 2000)<br />
## On Linux it uses unixODBC + FreeTDS (packages unixodbc or iodbc, and tdsodbc). Since 2012 there is also a Microsoft SQL Server ODBC Driver 1.0 for Linux which is a binary product (no open source) and provides native connectivity, but was released only for 64 bits and only for RedHat.<br />
<br />
Please see the FPC and Lazarus help files for details on using SQLDB with Sybase ASE and MSSQL Server.<br />
<br />
Note1: In any of the above forms, if you use native Microsoft Libraries (over Windows) it could be possible to connect to remote server with Named Pipes or with TCP/IP with fixed port (like 1433). If you use Wine in Linux only FreeTDS libraries are working, native libraries or Named Pipes will not work in Wine. On the other hand, if you use FreeTDS libraries (in Windows or Linux), connecting with Named Pipes is not supported by FreeTDS, only TCP/IP connections with fixed port (like 1433) are supported.<br />
<br />
Note2: Lazarus 1.0 was released with FPC 2.6.0 and does not include TMSSQLConnection or TSybaseConnection. If you want these, it might be easiest to download a snapshot of the latest Lazarus built with FPC 2.6.1, optinally installing that in a directory different from your Lazarus 1.0 version. You can use --primary-config-path to set up a separate environment for the Lazarus snapshot (see [[Multiple_Lazarus]])<br />
<br />
== Lazarus and ODBC ==<br />
ODBC is a general database connection standard which is available on Linux, Windows and OSX. You will need an ODBC driver from your database vendor and set up an ODBC "data source" (also known as DSN).<br />
You can use the SQLDB components (TODBCConnection) to connect to an ODBC data soruce.<br />
See [[ODBCConn]] for more details and examples<br />
<br />
== Lazarus and Oracle ==<br />
* Acces methods include:<br />
# Built-in SQLDB support<br />
# Zeos<br />
<br />
== Lazarus and PostgreSQL ==<br />
* Please see [[postgres]] for details on various access methods, which include:<br />
# Built-in SQLdb support. Use component '''TPQConnection''' from palette '''SQLdb'''<br />
# Zeos. Use component '''TZConnection''' with protocol 'postgresql' from palette '''Zeos Access'''<br />
<br />
== Lazarus and SQLite ==<br />
SQLite is an embedded database; the database code can be distributed as a library (.dll/.so/.dylib) with your application to make it self-contained (comparable to Firebird embedded). SQLite is quite popular due to its relative simplicity, speed, small size and cross-platform support.<br />
<br />
Please see the [[SQLite]] page for details on various access methods, which include:<br />
# Built-in SQLDb support<br />
# Zeos<br />
# SQLitePass <br />
# TSQLite3Dataset<br />
<br />
== Lazarus and dBase ==<br />
<br />
[[user:Tonymaro|Tony Maro]]<br />
<br />
You might also want to visit the [[Lazarus Tdbf Tutorial|TDbf Tutorial page]]<br />
<br />
FPC includes a simple database component that is similar in function to the Delphi TTable component called "TDbf" ([http://tdbf.sourceforge.net/ TDbf Website]) that supports a subset of features for dBase files. It is not installed by default, so you will first need to install the Lazarus package from the "lazarus/components/tdbf" directory and rebuild your Lazarus IDE. It will then appear next to the TDatasource in your component palette (Data Access tab).<br />
<br />
The TDbf component has an advantage over other database components in that it doesn't require any sort of runtime database engine. However it's not the best option for large database applications.<br />
<br />
It's very easy to use. Simply drop a TDbf on your form, set the runtime path to the directory that your database files will be in, set the table name, and link it to your TDatasource component.<br />
<br />
Real functionality requires a bit more effort, however. If a table doesn't already exist, you'll need to create it programmatically, unless there's a compatible table designer I'm not familiar with.<br />
Note: Current version of OpenOffice/LibreOffice (3.x) contains OpenOffice Base, which can create dbf files in a somewhat user-friendly way.<br />
<br />
Attempting to open a nonexistent table will generate an error. Tables can be created programmatically through the component after the runtime path and table name are set.<br />
<br />
For instance, to create a table called "dvds" to store your DVD collection you would drop it on your form, set the runtime path, and set the table name to "dvds". The resulting file will be called "dvds.dbf".<br />
<br />
In your code, insert the following:<br />
<br />
<syntaxhighlight>Dbf1.FilePathFull := '/path/to/my/database';<br />
Dbf1.TableName := 'dvds';<br />
With Dbf1.FieldDefs do begin<br />
Add('Name', ftString, 80, True);<br />
Add('Description', ftMemo, 0, False);<br />
Add('Rating', ftString, 5, False);<br />
end;<br />
Dbf1.CreateTable;</syntaxhighlight><br />
<br />
When this code is run, your DVD collection table will be created. After that, all data aware components linked through the TDatasource to this component will allow easy access to the data. <br />
<br />
Adding an index is a little different from your typical TTable. It must be done after the database is open. You use the same method also to rebuild the indices. For instance:<br />
<br />
<syntaxhighlight>Dbf1.Exclusive := True;<br />
Dbf1.Open;<br />
Dbf1.AddIndex('dvdsname','Name',[ixPrimary, ixUnique, ixCaseInsensitive]);<br />
Dbf1.AddIndex('rating.ndx', 'Rating', [ixCaseInsensitive]);<br />
Dbf1.Close;</syntaxhighlight><br />
<br />
The first (primary) index will be a file called "dvdsname.mdx" and the second will be a file named "rating.ndx" so in a multiple table database you must be careful not to use the same file name again.<br />
<br />
Please see [[Lazarus Tdbf Tutorial|TDbf Tutorial page]] for more details, but hopefully this will get those old Delphi programmers up and running with databases in Lazarus!<br />
<br />
===Searching and Displaying a data set===<br />
<br />
[[user:svbfieldview.net|Simon Batty]]<br />
<br />
In this example I wanted to search a database of books for all the titles an author has listed<br />
and then display the list in a memo box<br />
<syntaxhighlight>Dbf1.FilePathFull := '/home/somelocatio/database_location/'; // path to the database directory<br />
Dbf1.TableName := 'books.dbase'; // database file (including extension)<br />
DbF1.Open;<br />
memo1.Clear; // clear the memo box<br />
<br />
Dbf1.FilterOptions := [foCaseInsensitive];<br />
Df1.Filter := 'AU=' + QuotedStr('anauthor'); // AU is the field name containing the authors<br />
<br />
Dbf1.Filtered := true; // This selects the filtered set<br />
Dbf1.First; // moves the the first filtered data<br />
while not dbf1.EOF do // prints the titles that match the author to the memo box<br />
begin<br />
memo1.Append(Dbf1.FieldByName('TI').AsString); // TI is the field name for titles<br />
dbf1.next; // use .next here NOT .findnext!<br />
end;<br />
Dbf1.Close;</syntaxhighlight> <br />
<br />
Note that you can use Ddf1.findfirst to get the first record in the filtered set, then use <br />
Dbf1.next to move though the data. I found that using Dbf1.Findnext just causes the program to hang. <br />
<br />
This database was generated using TurboBD that came with the Kylix 1. I cannot get TurboBD tables to work with Lazarus, however you can download a command line tool from TurboDB's website that allows you to convert TurboDB table to other formats.<br />
<br />
== Using TSdfDataset and TFixedDataset ==<br />
<br />
TSdfDataset and TFixedDataset are two simple datasets which offer a very simple textual storage format. These datasets are very convenient for small databases, because they are fully implemented as an object pascal unit, and thus require no external libraries, and because their textual format allows them to be easely edited with a text editor.<br />
<br />
To start with this formats, a initial database file should be created. The format is very simple, so use a text editor to do this.<br />
<br />
Bellow is a sample database for TSdfDataset. Note that the first line has the names of the fields and that we are using commas as separators:<br />
<br />
<pre>ID,NAMEEN,NAMEPT,HEIGHT,WIDTH,PINS,DRAWINGCODE<br />
1,resistor,resistor,1,1,1,LINE<br />
2,capacitor,capacitor,1,1,1,LINE<br />
3,transistor npn,transistor npn</pre><br />
<br />
And here is an example database for using with TFixedDataset. Each record occupies a fixed amount of space, and if the field is smaller then it, spaces should be used to fill the remaining size.<br />
<br />
<pre>Name = 15 chars; Surname = 15 chars; Tell = 10 chars; e_mail = 20 chars;<br />
Piet Pompies piet@pompies.net</pre><br />
<br />
=== Using the datasets directly ===<br />
<br />
Sometimes it is useful to create the dataset and work with it completely in code, and the following code will do exactly this. Note some peculiarities of TSdfDataset/TFixedDataset:<br />
<br />
* The lines in the database can have a maximum size of about 300. A fix is being researched.<br />
* It is necessary to add the field definitions. Some datasets are able to fill this information alone from the database file<br />
* One should set FirstLineAsSchema to true, to indicate that the first line includes the field names and positions<br />
* The Delimiter property holds the separator for the fields. It will not be possible to use this char in strings in the database. Similarly it will not be possible to have lineendings in the database because they mark the change between records. It's possible to overcome this by substituting the needed comma or line ending with another not often used char, like # for example. So that when showing the data on screen all # chars could be converted to line endings and the inverse when storing data back to the database. The ReplaceString routine is useful here.<br />
<br />
<syntaxhighlight><br />
uses sdfdata, db;<br />
<br />
constructor TComponentsDatabase.Create;<br />
var<br />
FDataset: TSdfDataset;<br />
begin<br />
inherited Create;<br />
<br />
FDataset := TSdfDataset.Create(nil);<br />
FDataset.FileName := vConfigurations.ComponentsDBFile;<br />
<br />
// Not necessary with TSdfDataset<br />
// FDataset.TableName := STR_DB_COMPONENTS_TABLE;<br />
// FDataset.PrimaryKey := STR_DB_COMPONENTS_ID;<br />
<br />
// Adds field definitions<br />
FDataset.FieldDefs.Add('ID', ftString);<br />
FDataset.FieldDefs.Add('NAMEEN', ftString);<br />
FDataset.FieldDefs.Add('NAMEPT', ftString);<br />
FDataset.FieldDefs.Add('HEIGHT', ftString);<br />
FDataset.FieldDefs.Add('WIDTH', ftString);<br />
FDataset.FieldDefs.Add('PINS', ftString);<br />
FDataset.FieldDefs.Add('DRAWINGCODE', ftString);<br />
<br />
// Necessary for TSdfDataset<br />
FDataset.Delimiter := ',';<br />
FDataset.FirstLineAsSchema := True;<br />
<br />
FDataset.Active := True;<br />
<br />
// Sets the initial record<br />
CurrentRecNo := 1;<br />
FDataset.First;<br />
end;</syntaxhighlight><br />
<br />
When using TSdfDataset directly be aware that RecNo, although it is implemented, does not work as a way to move through the dataset whether reading or writing records. The standard navigation routines like First, Next, Prior and Last work as expected, so you need to use them rather than RecNo.<br />
If you are used to using absolute record numbers to navigate around a database you can implement your own version of RecNo. Declare a global longint variable called CurrentRecNo which will hold the current RecNo value. Remember that this variable will have the same convention as RecNo, so the first record has number 1 (it is not zero-based). After activating the database initialize the database to the first record with TSdfDataset.First and set CurrentRecNo := 1<br />
<br />
<syntaxhighlight>{@@<br />
Moves to the desired record using TDataset.Next and TDataset.Prior<br />
This avoids using TDataset.RecNo which doesn't navigate reliably in any dataset.<br />
<br />
@param AID Indicates the record number. The first record has number 1<br />
}<br />
procedure TComponentsDatabase.GoToRec(AID: Integer);<br />
begin<br />
// We are before the desired record, move forward<br />
if CurrentRecNo < AID then<br />
begin<br />
while (not FDataset.EOF) and (CurrentRecNo < AID) do<br />
begin<br />
FDataset.Next;<br />
FDataset.CursorPosChanged;<br />
Inc(CurrentRecNo);<br />
end;<br />
end<br />
// We are after the desired record, move back<br />
else if CurrentRecNo > AID then<br />
begin<br />
while (CurrentRecNo >= 1) and (CurrentRecNo > AID) do<br />
begin<br />
FDataset.Prior;<br />
FDataset.CursorPosChanged;<br />
Dec(CurrentRecNo);<br />
end;<br />
end;<br />
end;</syntaxhighlight><br />
<br />
=== Using with data-aware controls ===<br />
<br />
== Lazarus and Advantage Database Server ==<br />
* Please see [[Advantage Database Server]] for details on using Advantage Database Server<br />
<br />
==See also==<br />
* [[Database_field_type]]<br />
* [[Databases]]<br />
* [[Databases in Lazarus]]<br />
* [[Firebird in action]]<br />
* [[How to write in-memory database applications in Lazarus/FPC]]<br />
* [[Lazarus DB Faq]]<br />
* [[Lazarus Tdbf Tutorial]]<br />
* [[MS Access]]<br />
* [[multi-tier_options_with_fpc|Multi-tier options with FPC]]<br />
* [[MySQLDatabases]]<br />
* [[ODBCConn]]<br />
* [[SQLdb Tutorial1]]<br />
* [[SqlDBHowto]]<br />
* [[SQLite]]<br />
* [[tiOPF]] - a free and open source Object Persistence Framework.<br />
* [[Zeos tutorial]]<br />
<br />
==External links==<br />
<br />
* [http://pdo.sourceforge.net Pascal Data Objects] - a database API that worked for both FPC and Delphi and utilises native MySQL libraries for version 4.1 and 5.0 and Firebird SQL 1.5, and 2.0. It's inspired by PHP's PDO class.<br />
* [http://lazaruszeos.blogspot.com Zeos+SQLite Tutorial] - Good tutorial using screenshots and screencasts it explain how to use SQLite and Zeos, spanish (google translate does a good work in translating it to english)<br />
<br />
<br />
[[Category:Databases]]<br />
[[Category:Tutorials]]</div>Mario13https://wiki.freepascal.org/index.php?title=Lazarus_Database_Overview&diff=62558Lazarus Database Overview2012-10-08T18:37:05Z<p>Mario13: /* Lazarus and MSSQL/Sybase */</p>
<hr />
<div>{{Translate}}<br />
<br />
== Overview ==<br />
<br />
This article is an overview of the which databases can work with Lazarus.<br />
<br />
Lazarus supports several databases out of the box (using e.g. the SQLDB framework), however the developer must install the required packages (client libraries) for each one. <br />
<br />
You can access the database through code or by dropping components on a form. The data-aware components represent fields and are connected by setting the DataSource property to point to a TDataSource. The Datasource represents a table and is connected to the database components (examples: ''TPSQLDatabase'', ''TSQLiteDataSet'') by setting the DataSet property. The data-aware components are located on the "Data Controls" tab. The Datasource and the database controls are located on the "Data Access" tab.<br />
<br />
== Lazarus and Interbase / Firebird ==<br />
* Please see [[Firebird_in_action|Firebird in action]] for details on various access methods, which include<br />
# Built-in SQLDB support<br />
# FBLib<br />
# IBX<br />
# PDO<br />
# Zeos<br />
<br />
For a tutorial that leads you through creating a Lazarus GUI for a Firebird database, see:<br />
* [[SQLdb Tutorial1]]<br />
<br />
<br />
== Lazarus and MySQL ==<br />
* Please see [[mysql]] for details on various access methods, which include:<br />
# Built-in SQLDB support<br />
# PDO<br />
# Zeos<br />
<br />
== Lazarus and MSSQL/Sybase ==<br />
You can connect to Microsoft SQL Server databases using<br />
# The built-in '''SQLdb''' (recent Lazarus/FPC 2.6.1+): '''TMSSQLConnection''' (MS SQL) and '''TSybaseConnection''' (Sybase ASE)<br />
## On Windows by default it use FreeTDS library '''dblib.dll'''. By modifying FPC file '''dblib.pas''' it could use native library ntwdblib.dll (in this case FPC needs to be recompiled).<br />
## On Linux by default it use '''libsybdb.so''' which is FreeTDS library (for example, in Debian is in package '''libsybd5''').<br />
# '''Zeos''' component '''TZConnection''' (latest CVS, see links to Zeos elsewhere on this page)<br />
## On Windows you can choose between native library ntwdblib.dll (protocol '''mssql''') or FreeTDS libraries (protocol '''FreeTDS_MsSQL-nnnn''') where nnnn is one of four variants depending on the server version. For Delphi (not Lazarus) there is also another Zeos protocol '''ado''' for MSSQL 2005 or later. Using protocols mssql or ado generates code not platform independient.<br />
## On Linux the only way is with FreeTDS protocols and libraries (you should use '''libsybdb.so''').<br />
# '''ODBC''' (MSSQL and Sybase ASE) with SQLdb '''TODBCConnection'''<br />
## On Windows it uses native ODBC Microsoft libraries (like sqlsrv32.dll for MSSQL 2000)<br />
## On Linux it uses unixODBC + FreeTDS (packages unixodbc or iodbc, and tdsodbc). Since 2012 there is also a Microsoft SQL Server ODBC Driver 1.0 for Linux which is a binary product (no open source) and provides native connectivity, but was released only for 64 bits and only for RedHat.<br />
<br />
Please see the FPC and Lazarus help files for details on using SQLDB with Sybase ASE and MSSQL Server.<br />
<br />
Note1: In any of the above forms, if you use native Microsoft Libraries (over Windows) it could be possible to connect to remote server with Named Pipes or with TCP/IP with fixed port (like 1433). If you use Wine in Linux only FreeTDS libraries are working, native libraries or Named Pipes will not work in Wine. On the other hand, if you use FreeTDS libraries (in Windows or Linux), connecting with Named Pipes is not supported by FreeTDS, only TCP/IP connections with fixed port (like 1433) are supported.<br />
<br />
Note2: Lazarus 1.0 was released with FPC 2.6.0 and does not include TMSSQLConnection or TSybaseConnection. If you want these, it might be easiest to download a snapshot of the latest Lazarus built with FPC 2.6.1, optinally installing that in a directory different from your Lazarus 1.0 version. You can use --primary-config-path to set up a separate environment for the Lazarus snapshot (see [[Multiple_Lazarus]])<br />
<br />
== Lazarus and ODBC ==<br />
ODBC is a general database connection standard which is available on Linux, Windows and OSX. You will need an ODBC driver from your database vendor and set up an ODBC "data source" (also known as DSN).<br />
You can use the SQLDB components (TODBCConnection) to connect to an ODBC data soruce.<br />
See [[ODBCConn]] for more details and examples<br />
<br />
== Lazarus and Oracle ==<br />
* Acces methods include:<br />
# Built-in SQLDB support<br />
# Zeos<br />
<br />
== Lazarus and PostgreSQL ==<br />
* Please see [[postgres]] for details on various access methods, which include:<br />
# Built-in SQLdb support. Use component '''TPQConnection''' from palette '''SQLdb'''<br />
# Zeos. Use component '''TZConnection''' with protocol 'postgresql' from palette '''Zeos Access'''<br />
<br />
== Lazarus and SQLite ==<br />
SQLite is an embedded database; the database code can be distributed as a library (.dll/.so/.dylib) with your application to make it self-contained (comparable to Firebird embedded). SQLite is quite popular due to its relative simplicity, speed, small size and cross-platform support.<br />
<br />
Please see the [[SQLite]] page for details on various access methods, which include:<br />
# Built-in SQLDb support<br />
# Zeos<br />
# SQLitePass <br />
# TSQLite3Dataset<br />
<br />
== Lazarus and dBase ==<br />
<br />
[[user:Tonymaro|Tony Maro]]<br />
<br />
You might also want to visit the [[Lazarus Tdbf Tutorial|TDbf Tutorial page]]<br />
<br />
FPC includes a simple database component that is similar in function to the Delphi TTable component called "TDbf" ([http://tdbf.sourceforge.net/ TDbf Website]) that supports a subset of features for dBase files. It is not installed by default, so you will first need to install the Lazarus package from the "lazarus/components/tdbf" directory and rebuild your Lazarus IDE. It will then appear next to the TDatasource in your component palette (Data Access tab).<br />
<br />
The TDbf component has an advantage over other database components in that it doesn't require any sort of runtime database engine. However it's not the best option for large database applications.<br />
<br />
It's very easy to use. Simply drop a TDbf on your form, set the runtime path to the directory that your database files will be in, set the table name, and link it to your TDatasource component.<br />
<br />
Real functionality requires a bit more effort, however. If a table doesn't already exist, you'll need to create it programmatically, unless there's a compatible table designer I'm not familiar with.<br />
Note: Current version of OpenOffice/LibreOffice (3.x) contains OpenOffice Base, which can create dbf files in a somewhat user-friendly way.<br />
<br />
Attempting to open a nonexistent table will generate an error. Tables can be created programmatically through the component after the runtime path and table name are set.<br />
<br />
For instance, to create a table called "dvds" to store your DVD collection you would drop it on your form, set the runtime path, and set the table name to "dvds". The resulting file will be called "dvds.dbf".<br />
<br />
In your code, insert the following:<br />
<br />
<syntaxhighlight>Dbf1.FilePathFull := '/path/to/my/database';<br />
Dbf1.TableName := 'dvds';<br />
With Dbf1.FieldDefs do begin<br />
Add('Name', ftString, 80, True);<br />
Add('Description', ftMemo, 0, False);<br />
Add('Rating', ftString, 5, False);<br />
end;<br />
Dbf1.CreateTable;</syntaxhighlight><br />
<br />
When this code is run, your DVD collection table will be created. After that, all data aware components linked through the TDatasource to this component will allow easy access to the data. <br />
<br />
Adding an index is a little different from your typical TTable. It must be done after the database is open. You use the same method also to rebuild the indices. For instance:<br />
<br />
<syntaxhighlight>Dbf1.Exclusive := True;<br />
Dbf1.Open;<br />
Dbf1.AddIndex('dvdsname','Name',[ixPrimary, ixUnique, ixCaseInsensitive]);<br />
Dbf1.AddIndex('rating.ndx', 'Rating', [ixCaseInsensitive]);<br />
Dbf1.Close;</syntaxhighlight><br />
<br />
The first (primary) index will be a file called "dvdsname.mdx" and the second will be a file named "rating.ndx" so in a multiple table database you must be careful not to use the same file name again.<br />
<br />
Please see [[Lazarus Tdbf Tutorial|TDbf Tutorial page]] for more details, but hopefully this will get those old Delphi programmers up and running with databases in Lazarus!<br />
<br />
===Searching and Displaying a data set===<br />
<br />
[[user:svbfieldview.net|Simon Batty]]<br />
<br />
In this example I wanted to search a database of books for all the titles an author has listed<br />
and then display the list in a memo box<br />
<syntaxhighlight>Dbf1.FilePathFull := '/home/somelocatio/database_location/'; // path to the database directory<br />
Dbf1.TableName := 'books.dbase'; // database file (including extension)<br />
DbF1.Open;<br />
memo1.Clear; // clear the memo box<br />
<br />
Dbf1.FilterOptions := [foCaseInsensitive];<br />
Df1.Filter := 'AU=' + QuotedStr('anauthor'); // AU is the field name containing the authors<br />
<br />
Dbf1.Filtered := true; // This selects the filtered set<br />
Dbf1.First; // moves the the first filtered data<br />
while not dbf1.EOF do // prints the titles that match the author to the memo box<br />
begin<br />
memo1.Append(Dbf1.FieldByName('TI').AsString); // TI is the field name for titles<br />
dbf1.next; // use .next here NOT .findnext!<br />
end;<br />
Dbf1.Close;</syntaxhighlight> <br />
<br />
Note that you can use Ddf1.findfirst to get the first record in the filtered set, then use <br />
Dbf1.next to move though the data. I found that using Dbf1.Findnext just causes the program to hang. <br />
<br />
This database was generated using TurboBD that came with the Kylix 1. I cannot get TurboBD tables to work with Lazarus, however you can download a command line tool from TurboDB's website that allows you to convert TurboDB table to other formats.<br />
<br />
== Using TSdfDataset and TFixedDataset ==<br />
<br />
TSdfDataset and TFixedDataset are two simple datasets which offer a very simple textual storage format. These datasets are very convenient for small databases, because they are fully implemented as an object pascal unit, and thus require no external libraries, and because their textual format allows them to be easely edited with a text editor.<br />
<br />
To start with this formats, a initial database file should be created. The format is very simple, so use a text editor to do this.<br />
<br />
Bellow is a sample database for TSdfDataset. Note that the first line has the names of the fields and that we are using commas as separators:<br />
<br />
<pre>ID,NAMEEN,NAMEPT,HEIGHT,WIDTH,PINS,DRAWINGCODE<br />
1,resistor,resistor,1,1,1,LINE<br />
2,capacitor,capacitor,1,1,1,LINE<br />
3,transistor npn,transistor npn</pre><br />
<br />
And here is an example database for using with TFixedDataset. Each record occupies a fixed amount of space, and if the field is smaller then it, spaces should be used to fill the remaining size.<br />
<br />
<pre>Name = 15 chars; Surname = 15 chars; Tell = 10 chars; e_mail = 20 chars;<br />
Piet Pompies piet@pompies.net</pre><br />
<br />
=== Using the datasets directly ===<br />
<br />
Sometimes it is useful to create the dataset and work with it completely in code, and the following code will do exactly this. Note some peculiarities of TSdfDataset/TFixedDataset:<br />
<br />
* The lines in the database can have a maximum size of about 300. A fix is being researched.<br />
* It is necessary to add the field definitions. Some datasets are able to fill this information alone from the database file<br />
* One should set FirstLineAsSchema to true, to indicate that the first line includes the field names and positions<br />
* The Delimiter property holds the separator for the fields. It will not be possible to use this char in strings in the database. Similarly it will not be possible to have lineendings in the database because they mark the change between records. It's possible to overcome this by substituting the needed comma or line ending with another not often used char, like # for example. So that when showing the data on screen all # chars could be converted to line endings and the inverse when storing data back to the database. The ReplaceString routine is useful here.<br />
<br />
<syntaxhighlight><br />
uses sdfdata, db;<br />
<br />
constructor TComponentsDatabase.Create;<br />
var<br />
FDataset: TSdfDataset;<br />
begin<br />
inherited Create;<br />
<br />
FDataset := TSdfDataset.Create(nil);<br />
FDataset.FileName := vConfigurations.ComponentsDBFile;<br />
<br />
// Not necessary with TSdfDataset<br />
// FDataset.TableName := STR_DB_COMPONENTS_TABLE;<br />
// FDataset.PrimaryKey := STR_DB_COMPONENTS_ID;<br />
<br />
// Adds field definitions<br />
FDataset.FieldDefs.Add('ID', ftString);<br />
FDataset.FieldDefs.Add('NAMEEN', ftString);<br />
FDataset.FieldDefs.Add('NAMEPT', ftString);<br />
FDataset.FieldDefs.Add('HEIGHT', ftString);<br />
FDataset.FieldDefs.Add('WIDTH', ftString);<br />
FDataset.FieldDefs.Add('PINS', ftString);<br />
FDataset.FieldDefs.Add('DRAWINGCODE', ftString);<br />
<br />
// Necessary for TSdfDataset<br />
FDataset.Delimiter := ',';<br />
FDataset.FirstLineAsSchema := True;<br />
<br />
FDataset.Active := True;<br />
<br />
// Sets the initial record<br />
CurrentRecNo := 1;<br />
FDataset.First;<br />
end;</syntaxhighlight><br />
<br />
When using TSdfDataset directly be aware that RecNo, although it is implemented, does not work as a way to move through the dataset whether reading or writing records. The standard navigation routines like First, Next, Prior and Last work as expected, so you need to use them rather than RecNo.<br />
If you are used to using absolute record numbers to navigate around a database you can implement your own version of RecNo. Declare a global longint variable called CurrentRecNo which will hold the current RecNo value. Remember that this variable will have the same convention as RecNo, so the first record has number 1 (it is not zero-based). After activating the database initialize the database to the first record with TSdfDataset.First and set CurrentRecNo := 1<br />
<br />
<syntaxhighlight>{@@<br />
Moves to the desired record using TDataset.Next and TDataset.Prior<br />
This avoids using TDataset.RecNo which doesn't navigate reliably in any dataset.<br />
<br />
@param AID Indicates the record number. The first record has number 1<br />
}<br />
procedure TComponentsDatabase.GoToRec(AID: Integer);<br />
begin<br />
// We are before the desired record, move forward<br />
if CurrentRecNo < AID then<br />
begin<br />
while (not FDataset.EOF) and (CurrentRecNo < AID) do<br />
begin<br />
FDataset.Next;<br />
FDataset.CursorPosChanged;<br />
Inc(CurrentRecNo);<br />
end;<br />
end<br />
// We are after the desired record, move back<br />
else if CurrentRecNo > AID then<br />
begin<br />
while (CurrentRecNo >= 1) and (CurrentRecNo > AID) do<br />
begin<br />
FDataset.Prior;<br />
FDataset.CursorPosChanged;<br />
Dec(CurrentRecNo);<br />
end;<br />
end;<br />
end;</syntaxhighlight><br />
<br />
=== Using with data-aware controls ===<br />
<br />
== Lazarus and Advantage Database Server ==<br />
* Please see [[Advantage Database Server]] for details on using Advantage Database Server<br />
<br />
==See also==<br />
* [[Database_field_type]]<br />
* [[Databases]]<br />
* [[Databases in Lazarus]]<br />
* [[Firebird in action]]<br />
* [[How to write in-memory database applications in Lazarus/FPC]]<br />
* [[Lazarus DB Faq]]<br />
* [[Lazarus Tdbf Tutorial]]<br />
* [[MS Access]]<br />
* [[multi-tier_options_with_fpc|Multi-tier options with FPC]]<br />
* [[MySQLDatabases]]<br />
* [[ODBCConn]]<br />
* [[SQLdb Tutorial1]]<br />
* [[SqlDBHowto]]<br />
* [[SQLite]]<br />
* [[tiOPF]] - a free and open source Object Persistence Framework.<br />
* [[Zeos tutorial]]<br />
<br />
==External links==<br />
<br />
* [http://pdo.sourceforge.net Pascal Data Objects] - a database API that worked for both FPC and Delphi and utilises native MySQL libraries for version 4.1 and 5.0 and Firebird SQL 1.5, and 2.0. It's inspired by PHP's PDO class.<br />
* [http://lazaruszeos.blogspot.com Zeos+SQLite Tutorial] - Good tutorial using screenshots and screencasts it explain how to use SQLite and Zeos, spanish (google translate does a good work in translating it to english)<br />
<br />
<br />
[[Category:Databases]]<br />
[[Category:Tutorials]]</div>Mario13https://wiki.freepascal.org/index.php?title=Lazarus_Database_Overview&diff=62557Lazarus Database Overview2012-10-08T18:27:42Z<p>Mario13: /* Lazarus and MSSQL/Sybase */</p>
<hr />
<div>{{Translate}}<br />
<br />
== Overview ==<br />
<br />
This article is an overview of the which databases can work with Lazarus.<br />
<br />
Lazarus supports several databases out of the box (using e.g. the SQLDB framework), however the developer must install the required packages (client libraries) for each one. <br />
<br />
You can access the database through code or by dropping components on a form. The data-aware components represent fields and are connected by setting the DataSource property to point to a TDataSource. The Datasource represents a table and is connected to the database components (examples: ''TPSQLDatabase'', ''TSQLiteDataSet'') by setting the DataSet property. The data-aware components are located on the "Data Controls" tab. The Datasource and the database controls are located on the "Data Access" tab.<br />
<br />
== Lazarus and Interbase / Firebird ==<br />
* Please see [[Firebird_in_action|Firebird in action]] for details on various access methods, which include<br />
# Built-in SQLDB support<br />
# FBLib<br />
# IBX<br />
# PDO<br />
# Zeos<br />
<br />
For a tutorial that leads you through creating a Lazarus GUI for a Firebird database, see:<br />
* [[SQLdb Tutorial1]]<br />
<br />
<br />
== Lazarus and MySQL ==<br />
* Please see [[mysql]] for details on various access methods, which include:<br />
# Built-in SQLDB support<br />
# PDO<br />
# Zeos<br />
<br />
== Lazarus and MSSQL/Sybase ==<br />
You can connect to Microsoft SQL Server databases using<br />
# The built-in SQLdb (recent Lazarus/FPC 2.6.1+): '''TMSSQLConnection''' (MS SQL) and '''TSybaseConnection''' (Sybase ASE)<br />
## On Windows by default it use FreeTDS library '''dblib.dll'''. By modifying FPC file '''dblib.pas''' it could use native library ntwdblib.dll (in this case FPC needs to be recompiled).<br />
## On Linux by default it use '''libsybdb.so''' which is FreeTDS library (for example, in Debian is in package '''libsybd5''').<br />
# Zeos '''TZConnection''' (latest CVS, see links to Zeos elsewhere on this page)<br />
## On Windows you can choose between native library ntwdblib.dll (protocol '''mssql''') or FreeTDS libraries (protocol '''FreeTDS_MsSQL-nnnn''') where nnnn is one of four variants depending on the server version. For Delphi (not Lazarus) there is also another Zeos native protocol '''ado''' for use with MSSQl 2005 or later. Using protocols mssql or ado generates code not plantform independient.<br />
## On Linux the only way is with FreeTDS protocols and libraries (you should use '''libsybdb.so''').<br />
# ODBC (MS SQL and Sybase ASE) with SQLdb '''TODBCConnection'''<br />
## On Windows it uses native ODBC Microsoft libraries (like sqlsrv32.dll for MSSQL 2000)<br />
## On Linux it uses unixODBC + FreeTDS (packages unixodbc or iodbc, and tdsodbc)<br />
Please see the FPC and Lazarus help files for details on using SQLDB with Sybase ASE and MS SQL Server.<br />
<br />
Note1: In any of the above forms, if you use native Microsoft Libraries (over Windows) it could be possible to connect to remote server with Named Pipes or with TCP/IP with fixed port (like 1433). If you use Wine in Linux only FreeTDS libraries are working, native libraries or Named Pipes will not work in Wine. On the other hand, if you use FreeTDS libraries (in Windows or Linux), connecting with Named Pipes is not supported by FreeTDS, only TCP/IP connections with fixed port (like 1433) are supported.<br />
<br />
Note2: Lazarus 1.0 was released with FPC 2.6.0 and does not include TMSSQLConnection or TSybaseConnection. If you want these, it might be easiest to download a snapshot of the latest Lazarus built with FPC 2.6.1, optinally installing that in a directory different from your Lazarus 1.0 version. You can use --primary-config-path to set up a separate environment for the Lazarus snapshot (see [[Multiple_Lazarus]])<br />
<br />
== Lazarus and ODBC ==<br />
ODBC is a general database connection standard which is available on Linux, Windows and OSX. You will need an ODBC driver from your database vendor and set up an ODBC "data source" (also known as DSN).<br />
You can use the SQLDB components (TODBCConnection) to connect to an ODBC data soruce.<br />
See [[ODBCConn]] for more details and examples<br />
<br />
== Lazarus and Oracle ==<br />
* Acces methods include:<br />
# Built-in SQLDB support<br />
# Zeos<br />
<br />
== Lazarus and PostgreSQL ==<br />
* Please see [[postgres]] for details on various access methods, which include:<br />
# Built-in SQLdb support. Use component '''TPQConnection''' from palette '''SQLdb'''<br />
# Zeos. Use component '''TZConnection''' with protocol 'postgresql' from palette '''Zeos Access'''<br />
<br />
== Lazarus and SQLite ==<br />
SQLite is an embedded database; the database code can be distributed as a library (.dll/.so/.dylib) with your application to make it self-contained (comparable to Firebird embedded). SQLite is quite popular due to its relative simplicity, speed, small size and cross-platform support.<br />
<br />
Please see the [[SQLite]] page for details on various access methods, which include:<br />
# Built-in SQLDb support<br />
# Zeos<br />
# SQLitePass <br />
# TSQLite3Dataset<br />
<br />
== Lazarus and dBase ==<br />
<br />
[[user:Tonymaro|Tony Maro]]<br />
<br />
You might also want to visit the [[Lazarus Tdbf Tutorial|TDbf Tutorial page]]<br />
<br />
FPC includes a simple database component that is similar in function to the Delphi TTable component called "TDbf" ([http://tdbf.sourceforge.net/ TDbf Website]) that supports a subset of features for dBase files. It is not installed by default, so you will first need to install the Lazarus package from the "lazarus/components/tdbf" directory and rebuild your Lazarus IDE. It will then appear next to the TDatasource in your component palette (Data Access tab).<br />
<br />
The TDbf component has an advantage over other database components in that it doesn't require any sort of runtime database engine. However it's not the best option for large database applications.<br />
<br />
It's very easy to use. Simply drop a TDbf on your form, set the runtime path to the directory that your database files will be in, set the table name, and link it to your TDatasource component.<br />
<br />
Real functionality requires a bit more effort, however. If a table doesn't already exist, you'll need to create it programmatically, unless there's a compatible table designer I'm not familiar with.<br />
Note: Current version of OpenOffice/LibreOffice (3.x) contains OpenOffice Base, which can create dbf files in a somewhat user-friendly way.<br />
<br />
Attempting to open a nonexistent table will generate an error. Tables can be created programmatically through the component after the runtime path and table name are set.<br />
<br />
For instance, to create a table called "dvds" to store your DVD collection you would drop it on your form, set the runtime path, and set the table name to "dvds". The resulting file will be called "dvds.dbf".<br />
<br />
In your code, insert the following:<br />
<br />
<syntaxhighlight>Dbf1.FilePathFull := '/path/to/my/database';<br />
Dbf1.TableName := 'dvds';<br />
With Dbf1.FieldDefs do begin<br />
Add('Name', ftString, 80, True);<br />
Add('Description', ftMemo, 0, False);<br />
Add('Rating', ftString, 5, False);<br />
end;<br />
Dbf1.CreateTable;</syntaxhighlight><br />
<br />
When this code is run, your DVD collection table will be created. After that, all data aware components linked through the TDatasource to this component will allow easy access to the data. <br />
<br />
Adding an index is a little different from your typical TTable. It must be done after the database is open. You use the same method also to rebuild the indices. For instance:<br />
<br />
<syntaxhighlight>Dbf1.Exclusive := True;<br />
Dbf1.Open;<br />
Dbf1.AddIndex('dvdsname','Name',[ixPrimary, ixUnique, ixCaseInsensitive]);<br />
Dbf1.AddIndex('rating.ndx', 'Rating', [ixCaseInsensitive]);<br />
Dbf1.Close;</syntaxhighlight><br />
<br />
The first (primary) index will be a file called "dvdsname.mdx" and the second will be a file named "rating.ndx" so in a multiple table database you must be careful not to use the same file name again.<br />
<br />
Please see [[Lazarus Tdbf Tutorial|TDbf Tutorial page]] for more details, but hopefully this will get those old Delphi programmers up and running with databases in Lazarus!<br />
<br />
===Searching and Displaying a data set===<br />
<br />
[[user:svbfieldview.net|Simon Batty]]<br />
<br />
In this example I wanted to search a database of books for all the titles an author has listed<br />
and then display the list in a memo box<br />
<syntaxhighlight>Dbf1.FilePathFull := '/home/somelocatio/database_location/'; // path to the database directory<br />
Dbf1.TableName := 'books.dbase'; // database file (including extension)<br />
DbF1.Open;<br />
memo1.Clear; // clear the memo box<br />
<br />
Dbf1.FilterOptions := [foCaseInsensitive];<br />
Df1.Filter := 'AU=' + QuotedStr('anauthor'); // AU is the field name containing the authors<br />
<br />
Dbf1.Filtered := true; // This selects the filtered set<br />
Dbf1.First; // moves the the first filtered data<br />
while not dbf1.EOF do // prints the titles that match the author to the memo box<br />
begin<br />
memo1.Append(Dbf1.FieldByName('TI').AsString); // TI is the field name for titles<br />
dbf1.next; // use .next here NOT .findnext!<br />
end;<br />
Dbf1.Close;</syntaxhighlight> <br />
<br />
Note that you can use Ddf1.findfirst to get the first record in the filtered set, then use <br />
Dbf1.next to move though the data. I found that using Dbf1.Findnext just causes the program to hang. <br />
<br />
This database was generated using TurboBD that came with the Kylix 1. I cannot get TurboBD tables to work with Lazarus, however you can download a command line tool from TurboDB's website that allows you to convert TurboDB table to other formats.<br />
<br />
== Using TSdfDataset and TFixedDataset ==<br />
<br />
TSdfDataset and TFixedDataset are two simple datasets which offer a very simple textual storage format. These datasets are very convenient for small databases, because they are fully implemented as an object pascal unit, and thus require no external libraries, and because their textual format allows them to be easely edited with a text editor.<br />
<br />
To start with this formats, a initial database file should be created. The format is very simple, so use a text editor to do this.<br />
<br />
Bellow is a sample database for TSdfDataset. Note that the first line has the names of the fields and that we are using commas as separators:<br />
<br />
<pre>ID,NAMEEN,NAMEPT,HEIGHT,WIDTH,PINS,DRAWINGCODE<br />
1,resistor,resistor,1,1,1,LINE<br />
2,capacitor,capacitor,1,1,1,LINE<br />
3,transistor npn,transistor npn</pre><br />
<br />
And here is an example database for using with TFixedDataset. Each record occupies a fixed amount of space, and if the field is smaller then it, spaces should be used to fill the remaining size.<br />
<br />
<pre>Name = 15 chars; Surname = 15 chars; Tell = 10 chars; e_mail = 20 chars;<br />
Piet Pompies piet@pompies.net</pre><br />
<br />
=== Using the datasets directly ===<br />
<br />
Sometimes it is useful to create the dataset and work with it completely in code, and the following code will do exactly this. Note some peculiarities of TSdfDataset/TFixedDataset:<br />
<br />
* The lines in the database can have a maximum size of about 300. A fix is being researched.<br />
* It is necessary to add the field definitions. Some datasets are able to fill this information alone from the database file<br />
* One should set FirstLineAsSchema to true, to indicate that the first line includes the field names and positions<br />
* The Delimiter property holds the separator for the fields. It will not be possible to use this char in strings in the database. Similarly it will not be possible to have lineendings in the database because they mark the change between records. It's possible to overcome this by substituting the needed comma or line ending with another not often used char, like # for example. So that when showing the data on screen all # chars could be converted to line endings and the inverse when storing data back to the database. The ReplaceString routine is useful here.<br />
<br />
<syntaxhighlight><br />
uses sdfdata, db;<br />
<br />
constructor TComponentsDatabase.Create;<br />
var<br />
FDataset: TSdfDataset;<br />
begin<br />
inherited Create;<br />
<br />
FDataset := TSdfDataset.Create(nil);<br />
FDataset.FileName := vConfigurations.ComponentsDBFile;<br />
<br />
// Not necessary with TSdfDataset<br />
// FDataset.TableName := STR_DB_COMPONENTS_TABLE;<br />
// FDataset.PrimaryKey := STR_DB_COMPONENTS_ID;<br />
<br />
// Adds field definitions<br />
FDataset.FieldDefs.Add('ID', ftString);<br />
FDataset.FieldDefs.Add('NAMEEN', ftString);<br />
FDataset.FieldDefs.Add('NAMEPT', ftString);<br />
FDataset.FieldDefs.Add('HEIGHT', ftString);<br />
FDataset.FieldDefs.Add('WIDTH', ftString);<br />
FDataset.FieldDefs.Add('PINS', ftString);<br />
FDataset.FieldDefs.Add('DRAWINGCODE', ftString);<br />
<br />
// Necessary for TSdfDataset<br />
FDataset.Delimiter := ',';<br />
FDataset.FirstLineAsSchema := True;<br />
<br />
FDataset.Active := True;<br />
<br />
// Sets the initial record<br />
CurrentRecNo := 1;<br />
FDataset.First;<br />
end;</syntaxhighlight><br />
<br />
When using TSdfDataset directly be aware that RecNo, although it is implemented, does not work as a way to move through the dataset whether reading or writing records. The standard navigation routines like First, Next, Prior and Last work as expected, so you need to use them rather than RecNo.<br />
If you are used to using absolute record numbers to navigate around a database you can implement your own version of RecNo. Declare a global longint variable called CurrentRecNo which will hold the current RecNo value. Remember that this variable will have the same convention as RecNo, so the first record has number 1 (it is not zero-based). After activating the database initialize the database to the first record with TSdfDataset.First and set CurrentRecNo := 1<br />
<br />
<syntaxhighlight>{@@<br />
Moves to the desired record using TDataset.Next and TDataset.Prior<br />
This avoids using TDataset.RecNo which doesn't navigate reliably in any dataset.<br />
<br />
@param AID Indicates the record number. The first record has number 1<br />
}<br />
procedure TComponentsDatabase.GoToRec(AID: Integer);<br />
begin<br />
// We are before the desired record, move forward<br />
if CurrentRecNo < AID then<br />
begin<br />
while (not FDataset.EOF) and (CurrentRecNo < AID) do<br />
begin<br />
FDataset.Next;<br />
FDataset.CursorPosChanged;<br />
Inc(CurrentRecNo);<br />
end;<br />
end<br />
// We are after the desired record, move back<br />
else if CurrentRecNo > AID then<br />
begin<br />
while (CurrentRecNo >= 1) and (CurrentRecNo > AID) do<br />
begin<br />
FDataset.Prior;<br />
FDataset.CursorPosChanged;<br />
Dec(CurrentRecNo);<br />
end;<br />
end;<br />
end;</syntaxhighlight><br />
<br />
=== Using with data-aware controls ===<br />
<br />
== Lazarus and Advantage Database Server ==<br />
* Please see [[Advantage Database Server]] for details on using Advantage Database Server<br />
<br />
==See also==<br />
* [[Database_field_type]]<br />
* [[Databases]]<br />
* [[Databases in Lazarus]]<br />
* [[Firebird in action]]<br />
* [[How to write in-memory database applications in Lazarus/FPC]]<br />
* [[Lazarus DB Faq]]<br />
* [[Lazarus Tdbf Tutorial]]<br />
* [[MS Access]]<br />
* [[multi-tier_options_with_fpc|Multi-tier options with FPC]]<br />
* [[MySQLDatabases]]<br />
* [[ODBCConn]]<br />
* [[SQLdb Tutorial1]]<br />
* [[SqlDBHowto]]<br />
* [[SQLite]]<br />
* [[tiOPF]] - a free and open source Object Persistence Framework.<br />
* [[Zeos tutorial]]<br />
<br />
==External links==<br />
<br />
* [http://pdo.sourceforge.net Pascal Data Objects] - a database API that worked for both FPC and Delphi and utilises native MySQL libraries for version 4.1 and 5.0 and Firebird SQL 1.5, and 2.0. It's inspired by PHP's PDO class.<br />
* [http://lazaruszeos.blogspot.com Zeos+SQLite Tutorial] - Good tutorial using screenshots and screencasts it explain how to use SQLite and Zeos, spanish (google translate does a good work in translating it to english)<br />
<br />
<br />
[[Category:Databases]]<br />
[[Category:Tutorials]]</div>Mario13https://wiki.freepascal.org/index.php?title=Lazarus_Database_Overview&diff=62551Lazarus Database Overview2012-10-08T15:24:00Z<p>Mario13: /* Lazarus and MSSQL/Sybase */</p>
<hr />
<div>{{Translate}}<br />
<br />
== Overview ==<br />
<br />
This article is an overview of the which databases can work with Lazarus.<br />
<br />
Lazarus supports several databases out of the box (using e.g. the SQLDB framework), however the developer must install the required packages (client libraries) for each one. <br />
<br />
You can access the database through code or by dropping components on a form. The data-aware components represent fields and are connected by setting the DataSource property to point to a TDataSource. The Datasource represents a table and is connected to the database components (examples: ''TPSQLDatabase'', ''TSQLiteDataSet'') by setting the DataSet property. The data-aware components are located on the "Data Controls" tab. The Datasource and the database controls are located on the "Data Access" tab.<br />
<br />
== Lazarus and Interbase / Firebird ==<br />
* Please see [[Firebird_in_action|Firebird in action]] for details on various access methods, which include<br />
# Built-in SQLDB support<br />
# FBLib<br />
# IBX<br />
# PDO<br />
# Zeos<br />
<br />
For a tutorial that leads you through creating a Lazarus GUI for a Firebird database, see:<br />
* [[SQLdb Tutorial1]]<br />
<br />
<br />
== Lazarus and MySQL ==<br />
* Please see [[mysql]] for details on various access methods, which include:<br />
# Built-in SQLDB support<br />
# PDO<br />
# Zeos<br />
<br />
== Lazarus and MSSQL/Sybase ==<br />
You can connect to Microsoft SQL Server databases using<br />
# The built-in SQLdb (recent Lazarus/FPC 2.6.1+): '''TMSSQLConnection''' (MS SQL) and '''TSybaseConnection''' (Sybase ASE)<br />
## On Windows by default it use FreeTDS library '''dblib.dll'''. By modifying FPC file '''dblib.pas''' it could use native library ntwdblib.dll (in this case FPC needs to be recompiled).<br />
## On Linux by default it use '''libsybdb.so''' which is FreeTDS library (for example, in Debian is in package '''libsybd5''').<br />
# Zeos '''TZConnection''' (latest CVS, see links to Zeos elsewhere on this page)<br />
## On Windows you can choose between native library ntwdblib.dll (protocol '''mssql''') or FreeTDS libraries (protocol '''FreeTDS_MsSQL-nnnn''') where nnnn is one of four variants depending on the server version. <br />
## On Linux the only way is with FreeTDS protocols and libraries (you should use '''libsybdb.so''').<br />
# ODBC (MS SQL and Sybase ASE) with SQLdb '''TODBCConnection'''<br />
## On Windows it uses native ODBC Microsoft libraries (like sqlsrv32.dll for SQL server 2000)<br />
## On Linux it uses unixODBC + FreeTDS (packages unixodbc or iodbc, and tdsodbc)<br />
Please see the FPC and Lazarus help files for details on using SQLDB with Sybase ASE and MS SQL Server.<br />
<br />
Note1: In any of the above forms, if you use native Microsoft Libraries (over Windows) it could be possible to connect to remote server with Named Pipes or with TCP/IP with fixed port (like 1433). If you use Wine in Linux only FreeTDS libraries are working, native libraries or Named Pipes will not work in Wine. On the other hand, if you use FreeTDS libraries (in Windows or Linux), connecting with Named Pipes is not supported by FreeTDS, only TCP/IP connections with fixed port (like 1433) are supported.<br />
<br />
Note2: Lazarus 1.0 was released with FPC 2.6.0 and does not include TMSSQLConnection or TSybaseConnection. If you want these, it might be easiest to download a snapshot of the latest Lazarus built with FPC 2.6.1, optinally installing that in a directory different from your Lazarus 1.0 version. You can use --primary-config-path to set up a separate environment for the Lazarus snapshot (see [[Multiple_Lazarus]])<br />
<br />
== Lazarus and ODBC ==<br />
ODBC is a general database connection standard which is available on Linux, Windows and OSX. You will need an ODBC driver from your database vendor and set up an ODBC "data source" (also known as DSN).<br />
You can use the SQLDB components (TODBCConnection) to connect to an ODBC data soruce.<br />
See [[ODBCConn]] for more details and examples<br />
<br />
== Lazarus and Oracle ==<br />
* Acces methods include:<br />
# Built-in SQLDB support<br />
# Zeos<br />
<br />
== Lazarus and PostgreSQL ==<br />
* Please see [[postgres]] for details on various access methods, which include:<br />
# Built-in SQLdb support. Use component '''TPQConnection''' from palette '''SQLdb'''<br />
# Zeos. Use component '''TZConnection''' with protocol 'postgresql' from palette '''Zeos Access'''<br />
<br />
== Lazarus and SQLite ==<br />
SQLite is an embedded database; the database code can be distributed as a library (.dll/.so/.dylib) with your application to make it self-contained (comparable to Firebird embedded). SQLite is quite popular due to its relative simplicity, speed, small size and cross-platform support.<br />
<br />
Please see the [[SQLite]] page for details on various access methods, which include:<br />
# Built-in SQLDb support<br />
# Zeos<br />
# SQLitePass <br />
# TSQLite3Dataset<br />
<br />
== Lazarus and dBase ==<br />
<br />
[[user:Tonymaro|Tony Maro]]<br />
<br />
You might also want to visit the [[Lazarus Tdbf Tutorial|TDbf Tutorial page]]<br />
<br />
FPC includes a simple database component that is similar in function to the Delphi TTable component called "TDbf" ([http://tdbf.sourceforge.net/ TDbf Website]) that supports a subset of features for dBase files. It is not installed by default, so you will first need to install the Lazarus package from the "lazarus/components/tdbf" directory and rebuild your Lazarus IDE. It will then appear next to the TDatasource in your component palette (Data Access tab).<br />
<br />
The TDbf component has an advantage over other database components in that it doesn't require any sort of runtime database engine. However it's not the best option for large database applications.<br />
<br />
It's very easy to use. Simply drop a TDbf on your form, set the runtime path to the directory that your database files will be in, set the table name, and link it to your TDatasource component.<br />
<br />
Real functionality requires a bit more effort, however. If a table doesn't already exist, you'll need to create it programmatically, unless there's a compatible table designer I'm not familiar with.<br />
Note: Current version of OpenOffice/LibreOffice (3.x) contains OpenOffice Base, which can create dbf files in a somewhat user-friendly way.<br />
<br />
Attempting to open a nonexistent table will generate an error. Tables can be created programmatically through the component after the runtime path and table name are set.<br />
<br />
For instance, to create a table called "dvds" to store your DVD collection you would drop it on your form, set the runtime path, and set the table name to "dvds". The resulting file will be called "dvds.dbf".<br />
<br />
In your code, insert the following:<br />
<br />
<syntaxhighlight>Dbf1.FilePathFull := '/path/to/my/database';<br />
Dbf1.TableName := 'dvds';<br />
With Dbf1.FieldDefs do begin<br />
Add('Name', ftString, 80, True);<br />
Add('Description', ftMemo, 0, False);<br />
Add('Rating', ftString, 5, False);<br />
end;<br />
Dbf1.CreateTable;</syntaxhighlight><br />
<br />
When this code is run, your DVD collection table will be created. After that, all data aware components linked through the TDatasource to this component will allow easy access to the data. <br />
<br />
Adding an index is a little different from your typical TTable. It must be done after the database is open. You use the same method also to rebuild the indices. For instance:<br />
<br />
<syntaxhighlight>Dbf1.Exclusive := True;<br />
Dbf1.Open;<br />
Dbf1.AddIndex('dvdsname','Name',[ixPrimary, ixUnique, ixCaseInsensitive]);<br />
Dbf1.AddIndex('rating.ndx', 'Rating', [ixCaseInsensitive]);<br />
Dbf1.Close;</syntaxhighlight><br />
<br />
The first (primary) index will be a file called "dvdsname.mdx" and the second will be a file named "rating.ndx" so in a multiple table database you must be careful not to use the same file name again.<br />
<br />
Please see [[Lazarus Tdbf Tutorial|TDbf Tutorial page]] for more details, but hopefully this will get those old Delphi programmers up and running with databases in Lazarus!<br />
<br />
===Searching and Displaying a data set===<br />
<br />
[[user:svbfieldview.net|Simon Batty]]<br />
<br />
In this example I wanted to search a database of books for all the titles an author has listed<br />
and then display the list in a memo box<br />
<syntaxhighlight>Dbf1.FilePathFull := '/home/somelocatio/database_location/'; // path to the database directory<br />
Dbf1.TableName := 'books.dbase'; // database file (including extension)<br />
DbF1.Open;<br />
memo1.Clear; // clear the memo box<br />
<br />
Dbf1.FilterOptions := [foCaseInsensitive];<br />
Df1.Filter := 'AU=' + QuotedStr('anauthor'); // AU is the field name containing the authors<br />
<br />
Dbf1.Filtered := true; // This selects the filtered set<br />
Dbf1.First; // moves the the first filtered data<br />
while not dbf1.EOF do // prints the titles that match the author to the memo box<br />
begin<br />
memo1.Append(Dbf1.FieldByName('TI').AsString); // TI is the field name for titles<br />
dbf1.next; // use .next here NOT .findnext!<br />
end;<br />
Dbf1.Close;</syntaxhighlight> <br />
<br />
Note that you can use Ddf1.findfirst to get the first record in the filtered set, then use <br />
Dbf1.next to move though the data. I found that using Dbf1.Findnext just causes the program to hang. <br />
<br />
This database was generated using TurboBD that came with the Kylix 1. I cannot get TurboBD tables to work with Lazarus, however you can download a command line tool from TurboDB's website that allows you to convert TurboDB table to other formats.<br />
<br />
== Using TSdfDataset and TFixedDataset ==<br />
<br />
TSdfDataset and TFixedDataset are two simple datasets which offer a very simple textual storage format. These datasets are very convenient for small databases, because they are fully implemented as an object pascal unit, and thus require no external libraries, and because their textual format allows them to be easely edited with a text editor.<br />
<br />
To start with this formats, a initial database file should be created. The format is very simple, so use a text editor to do this.<br />
<br />
Bellow is a sample database for TSdfDataset. Note that the first line has the names of the fields and that we are using commas as separators:<br />
<br />
<pre>ID,NAMEEN,NAMEPT,HEIGHT,WIDTH,PINS,DRAWINGCODE<br />
1,resistor,resistor,1,1,1,LINE<br />
2,capacitor,capacitor,1,1,1,LINE<br />
3,transistor npn,transistor npn</pre><br />
<br />
And here is an example database for using with TFixedDataset. Each record occupies a fixed amount of space, and if the field is smaller then it, spaces should be used to fill the remaining size.<br />
<br />
<pre>Name = 15 chars; Surname = 15 chars; Tell = 10 chars; e_mail = 20 chars;<br />
Piet Pompies piet@pompies.net</pre><br />
<br />
=== Using the datasets directly ===<br />
<br />
Sometimes it is useful to create the dataset and work with it completely in code, and the following code will do exactly this. Note some peculiarities of TSdfDataset/TFixedDataset:<br />
<br />
* The lines in the database can have a maximum size of about 300. A fix is being researched.<br />
* It is necessary to add the field definitions. Some datasets are able to fill this information alone from the database file<br />
* One should set FirstLineAsSchema to true, to indicate that the first line includes the field names and positions<br />
* The Delimiter property holds the separator for the fields. It will not be possible to use this char in strings in the database. Similarly it will not be possible to have lineendings in the database because they mark the change between records. It's possible to overcome this by substituting the needed comma or line ending with another not often used char, like # for example. So that when showing the data on screen all # chars could be converted to line endings and the inverse when storing data back to the database. The ReplaceString routine is useful here.<br />
<br />
<syntaxhighlight><br />
uses sdfdata, db;<br />
<br />
constructor TComponentsDatabase.Create;<br />
var<br />
FDataset: TSdfDataset;<br />
begin<br />
inherited Create;<br />
<br />
FDataset := TSdfDataset.Create(nil);<br />
FDataset.FileName := vConfigurations.ComponentsDBFile;<br />
<br />
// Not necessary with TSdfDataset<br />
// FDataset.TableName := STR_DB_COMPONENTS_TABLE;<br />
// FDataset.PrimaryKey := STR_DB_COMPONENTS_ID;<br />
<br />
// Adds field definitions<br />
FDataset.FieldDefs.Add('ID', ftString);<br />
FDataset.FieldDefs.Add('NAMEEN', ftString);<br />
FDataset.FieldDefs.Add('NAMEPT', ftString);<br />
FDataset.FieldDefs.Add('HEIGHT', ftString);<br />
FDataset.FieldDefs.Add('WIDTH', ftString);<br />
FDataset.FieldDefs.Add('PINS', ftString);<br />
FDataset.FieldDefs.Add('DRAWINGCODE', ftString);<br />
<br />
// Necessary for TSdfDataset<br />
FDataset.Delimiter := ',';<br />
FDataset.FirstLineAsSchema := True;<br />
<br />
FDataset.Active := True;<br />
<br />
// Sets the initial record<br />
CurrentRecNo := 1;<br />
FDataset.First;<br />
end;</syntaxhighlight><br />
<br />
When using TSdfDataset directly be aware that RecNo, although it is implemented, does not work as a way to move through the dataset whether reading or writing records. The standard navigation routines like First, Next, Prior and Last work as expected, so you need to use them rather than RecNo.<br />
If you are used to using absolute record numbers to navigate around a database you can implement your own version of RecNo. Declare a global longint variable called CurrentRecNo which will hold the current RecNo value. Remember that this variable will have the same convention as RecNo, so the first record has number 1 (it is not zero-based). After activating the database initialize the database to the first record with TSdfDataset.First and set CurrentRecNo := 1<br />
<br />
<syntaxhighlight>{@@<br />
Moves to the desired record using TDataset.Next and TDataset.Prior<br />
This avoids using TDataset.RecNo which doesn't navigate reliably in any dataset.<br />
<br />
@param AID Indicates the record number. The first record has number 1<br />
}<br />
procedure TComponentsDatabase.GoToRec(AID: Integer);<br />
begin<br />
// We are before the desired record, move forward<br />
if CurrentRecNo < AID then<br />
begin<br />
while (not FDataset.EOF) and (CurrentRecNo < AID) do<br />
begin<br />
FDataset.Next;<br />
FDataset.CursorPosChanged;<br />
Inc(CurrentRecNo);<br />
end;<br />
end<br />
// We are after the desired record, move back<br />
else if CurrentRecNo > AID then<br />
begin<br />
while (CurrentRecNo >= 1) and (CurrentRecNo > AID) do<br />
begin<br />
FDataset.Prior;<br />
FDataset.CursorPosChanged;<br />
Dec(CurrentRecNo);<br />
end;<br />
end;<br />
end;</syntaxhighlight><br />
<br />
=== Using with data-aware controls ===<br />
<br />
== Lazarus and Advantage Database Server ==<br />
* Please see [[Advantage Database Server]] for details on using Advantage Database Server<br />
<br />
==See also==<br />
* [[Database_field_type]]<br />
* [[Databases]]<br />
* [[Databases in Lazarus]]<br />
* [[Firebird in action]]<br />
* [[How to write in-memory database applications in Lazarus/FPC]]<br />
* [[Lazarus DB Faq]]<br />
* [[Lazarus Tdbf Tutorial]]<br />
* [[MS Access]]<br />
* [[multi-tier_options_with_fpc|Multi-tier options with FPC]]<br />
* [[MySQLDatabases]]<br />
* [[ODBCConn]]<br />
* [[SQLdb Tutorial1]]<br />
* [[SqlDBHowto]]<br />
* [[SQLite]]<br />
* [[tiOPF]] - a free and open source Object Persistence Framework.<br />
* [[Zeos tutorial]]<br />
<br />
==External links==<br />
<br />
* [http://pdo.sourceforge.net Pascal Data Objects] - a database API that worked for both FPC and Delphi and utilises native MySQL libraries for version 4.1 and 5.0 and Firebird SQL 1.5, and 2.0. It's inspired by PHP's PDO class.<br />
* [http://lazaruszeos.blogspot.com Zeos+SQLite Tutorial] - Good tutorial using screenshots and screencasts it explain how to use SQLite and Zeos, spanish (google translate does a good work in translating it to english)<br />
<br />
<br />
[[Category:Databases]]<br />
[[Category:Tutorials]]</div>Mario13https://wiki.freepascal.org/index.php?title=Lazarus_Database_Overview&diff=62550Lazarus Database Overview2012-10-08T15:21:45Z<p>Mario13: /* Lazarus and MSSQL/Sybase */</p>
<hr />
<div>{{Translate}}<br />
<br />
== Overview ==<br />
<br />
This article is an overview of the which databases can work with Lazarus.<br />
<br />
Lazarus supports several databases out of the box (using e.g. the SQLDB framework), however the developer must install the required packages (client libraries) for each one. <br />
<br />
You can access the database through code or by dropping components on a form. The data-aware components represent fields and are connected by setting the DataSource property to point to a TDataSource. The Datasource represents a table and is connected to the database components (examples: ''TPSQLDatabase'', ''TSQLiteDataSet'') by setting the DataSet property. The data-aware components are located on the "Data Controls" tab. The Datasource and the database controls are located on the "Data Access" tab.<br />
<br />
== Lazarus and Interbase / Firebird ==<br />
* Please see [[Firebird_in_action|Firebird in action]] for details on various access methods, which include<br />
# Built-in SQLDB support<br />
# FBLib<br />
# IBX<br />
# PDO<br />
# Zeos<br />
<br />
For a tutorial that leads you through creating a Lazarus GUI for a Firebird database, see:<br />
* [[SQLdb Tutorial1]]<br />
<br />
<br />
== Lazarus and MySQL ==<br />
* Please see [[mysql]] for details on various access methods, which include:<br />
# Built-in SQLDB support<br />
# PDO<br />
# Zeos<br />
<br />
== Lazarus and MSSQL/Sybase ==<br />
You can connect to Microsoft SQL Server databases using<br />
# The built-in SQLdb (recent Lazarus/FPC 2.6.1+): '''TMSSQLConnection''' (MS SQL) and '''TSybaseConnection''' (Sybase ASE)<br />
## On Windows by default it use FreeTDS library '''dblib.dll'''. By modifying FPC file '''dblib.pas''' it could use native library ntwdblib.dll (in this case FPC needs to be recompiled).<br />
## On Linux by default it use '''libsybdb.so''' which is FreeTDS library (for example, in Debian is in package '''libsybd5''').<br />
# Zeos '''TZConnection''' (latest CVS, see links to Zeos elsewhere on this page)<br />
## On Windows you can choose between native library ntwdblib.dll (protocol '''mssql''') or FreeTDS libraries (protocol '''FreeTDS_MsSQL-nnnn''') where nnnn is one of four variants depending on the server version. <br />
## On Linux the only way is with FreeTDS protocols and libraries (you should use '''libsybdb.so''').<br />
# ODBC (MS SQL and Sybase ASE) with SQLdb '''TODBCConnection'''<br />
## On Windows it uses native ODBC Microsoft libraries (like sqlsrv32.dll for SQL server 2000)<br />
## On Linux it uses unixODBC + FreeTDS (packages unixodbc or iodbc, and tdsodbc)<br />
Please see the FPC and Lazarus help files for details on using SQLDB with Sybase ASE and MS SQL Server.<br />
<br />
Note1: In any of the above forms, if you use native Microsoft Libraries (over Windows) it could be possible to connect to remote server with Named Pipes or with TCP/IP with fixed port (like 1433). If you use Wine in Linux only FreeTDS libraries are working, native libraries or Named Pipes will not work (for now). On the other hand, if you use FreeTDS libraries (in Windows or Linux), connecting with Named Pipes is not supported, only TCP/IP connections with fixed port (like 1433) are supported.<br />
<br />
Note2: Lazarus 1.0 was released with FPC 2.6.0 and does not include TMSSQLConnection or TSybaseConnection. If you want these, it might be easiest to download a snapshot of the latest Lazarus built with FPC 2.6.1, optinally installing that in a directory different from your Lazarus 1.0 version. You can use --primary-config-path to set up a separate environment for the Lazarus snapshot (see [[Multiple_Lazarus]])<br />
<br />
== Lazarus and ODBC ==<br />
ODBC is a general database connection standard which is available on Linux, Windows and OSX. You will need an ODBC driver from your database vendor and set up an ODBC "data source" (also known as DSN).<br />
You can use the SQLDB components (TODBCConnection) to connect to an ODBC data soruce.<br />
See [[ODBCConn]] for more details and examples<br />
<br />
== Lazarus and Oracle ==<br />
* Acces methods include:<br />
# Built-in SQLDB support<br />
# Zeos<br />
<br />
== Lazarus and PostgreSQL ==<br />
* Please see [[postgres]] for details on various access methods, which include:<br />
# Built-in SQLdb support. Use component '''TPQConnection''' from palette '''SQLdb'''<br />
# Zeos. Use component '''TZConnection''' with protocol 'postgresql' from palette '''Zeos Access'''<br />
<br />
== Lazarus and SQLite ==<br />
SQLite is an embedded database; the database code can be distributed as a library (.dll/.so/.dylib) with your application to make it self-contained (comparable to Firebird embedded). SQLite is quite popular due to its relative simplicity, speed, small size and cross-platform support.<br />
<br />
Please see the [[SQLite]] page for details on various access methods, which include:<br />
# Built-in SQLDb support<br />
# Zeos<br />
# SQLitePass <br />
# TSQLite3Dataset<br />
<br />
== Lazarus and dBase ==<br />
<br />
[[user:Tonymaro|Tony Maro]]<br />
<br />
You might also want to visit the [[Lazarus Tdbf Tutorial|TDbf Tutorial page]]<br />
<br />
FPC includes a simple database component that is similar in function to the Delphi TTable component called "TDbf" ([http://tdbf.sourceforge.net/ TDbf Website]) that supports a subset of features for dBase files. It is not installed by default, so you will first need to install the Lazarus package from the "lazarus/components/tdbf" directory and rebuild your Lazarus IDE. It will then appear next to the TDatasource in your component palette (Data Access tab).<br />
<br />
The TDbf component has an advantage over other database components in that it doesn't require any sort of runtime database engine. However it's not the best option for large database applications.<br />
<br />
It's very easy to use. Simply drop a TDbf on your form, set the runtime path to the directory that your database files will be in, set the table name, and link it to your TDatasource component.<br />
<br />
Real functionality requires a bit more effort, however. If a table doesn't already exist, you'll need to create it programmatically, unless there's a compatible table designer I'm not familiar with.<br />
Note: Current version of OpenOffice/LibreOffice (3.x) contains OpenOffice Base, which can create dbf files in a somewhat user-friendly way.<br />
<br />
Attempting to open a nonexistent table will generate an error. Tables can be created programmatically through the component after the runtime path and table name are set.<br />
<br />
For instance, to create a table called "dvds" to store your DVD collection you would drop it on your form, set the runtime path, and set the table name to "dvds". The resulting file will be called "dvds.dbf".<br />
<br />
In your code, insert the following:<br />
<br />
<syntaxhighlight>Dbf1.FilePathFull := '/path/to/my/database';<br />
Dbf1.TableName := 'dvds';<br />
With Dbf1.FieldDefs do begin<br />
Add('Name', ftString, 80, True);<br />
Add('Description', ftMemo, 0, False);<br />
Add('Rating', ftString, 5, False);<br />
end;<br />
Dbf1.CreateTable;</syntaxhighlight><br />
<br />
When this code is run, your DVD collection table will be created. After that, all data aware components linked through the TDatasource to this component will allow easy access to the data. <br />
<br />
Adding an index is a little different from your typical TTable. It must be done after the database is open. You use the same method also to rebuild the indices. For instance:<br />
<br />
<syntaxhighlight>Dbf1.Exclusive := True;<br />
Dbf1.Open;<br />
Dbf1.AddIndex('dvdsname','Name',[ixPrimary, ixUnique, ixCaseInsensitive]);<br />
Dbf1.AddIndex('rating.ndx', 'Rating', [ixCaseInsensitive]);<br />
Dbf1.Close;</syntaxhighlight><br />
<br />
The first (primary) index will be a file called "dvdsname.mdx" and the second will be a file named "rating.ndx" so in a multiple table database you must be careful not to use the same file name again.<br />
<br />
Please see [[Lazarus Tdbf Tutorial|TDbf Tutorial page]] for more details, but hopefully this will get those old Delphi programmers up and running with databases in Lazarus!<br />
<br />
===Searching and Displaying a data set===<br />
<br />
[[user:svbfieldview.net|Simon Batty]]<br />
<br />
In this example I wanted to search a database of books for all the titles an author has listed<br />
and then display the list in a memo box<br />
<syntaxhighlight>Dbf1.FilePathFull := '/home/somelocatio/database_location/'; // path to the database directory<br />
Dbf1.TableName := 'books.dbase'; // database file (including extension)<br />
DbF1.Open;<br />
memo1.Clear; // clear the memo box<br />
<br />
Dbf1.FilterOptions := [foCaseInsensitive];<br />
Df1.Filter := 'AU=' + QuotedStr('anauthor'); // AU is the field name containing the authors<br />
<br />
Dbf1.Filtered := true; // This selects the filtered set<br />
Dbf1.First; // moves the the first filtered data<br />
while not dbf1.EOF do // prints the titles that match the author to the memo box<br />
begin<br />
memo1.Append(Dbf1.FieldByName('TI').AsString); // TI is the field name for titles<br />
dbf1.next; // use .next here NOT .findnext!<br />
end;<br />
Dbf1.Close;</syntaxhighlight> <br />
<br />
Note that you can use Ddf1.findfirst to get the first record in the filtered set, then use <br />
Dbf1.next to move though the data. I found that using Dbf1.Findnext just causes the program to hang. <br />
<br />
This database was generated using TurboBD that came with the Kylix 1. I cannot get TurboBD tables to work with Lazarus, however you can download a command line tool from TurboDB's website that allows you to convert TurboDB table to other formats.<br />
<br />
== Using TSdfDataset and TFixedDataset ==<br />
<br />
TSdfDataset and TFixedDataset are two simple datasets which offer a very simple textual storage format. These datasets are very convenient for small databases, because they are fully implemented as an object pascal unit, and thus require no external libraries, and because their textual format allows them to be easely edited with a text editor.<br />
<br />
To start with this formats, a initial database file should be created. The format is very simple, so use a text editor to do this.<br />
<br />
Bellow is a sample database for TSdfDataset. Note that the first line has the names of the fields and that we are using commas as separators:<br />
<br />
<pre>ID,NAMEEN,NAMEPT,HEIGHT,WIDTH,PINS,DRAWINGCODE<br />
1,resistor,resistor,1,1,1,LINE<br />
2,capacitor,capacitor,1,1,1,LINE<br />
3,transistor npn,transistor npn</pre><br />
<br />
And here is an example database for using with TFixedDataset. Each record occupies a fixed amount of space, and if the field is smaller then it, spaces should be used to fill the remaining size.<br />
<br />
<pre>Name = 15 chars; Surname = 15 chars; Tell = 10 chars; e_mail = 20 chars;<br />
Piet Pompies piet@pompies.net</pre><br />
<br />
=== Using the datasets directly ===<br />
<br />
Sometimes it is useful to create the dataset and work with it completely in code, and the following code will do exactly this. Note some peculiarities of TSdfDataset/TFixedDataset:<br />
<br />
* The lines in the database can have a maximum size of about 300. A fix is being researched.<br />
* It is necessary to add the field definitions. Some datasets are able to fill this information alone from the database file<br />
* One should set FirstLineAsSchema to true, to indicate that the first line includes the field names and positions<br />
* The Delimiter property holds the separator for the fields. It will not be possible to use this char in strings in the database. Similarly it will not be possible to have lineendings in the database because they mark the change between records. It's possible to overcome this by substituting the needed comma or line ending with another not often used char, like # for example. So that when showing the data on screen all # chars could be converted to line endings and the inverse when storing data back to the database. The ReplaceString routine is useful here.<br />
<br />
<syntaxhighlight><br />
uses sdfdata, db;<br />
<br />
constructor TComponentsDatabase.Create;<br />
var<br />
FDataset: TSdfDataset;<br />
begin<br />
inherited Create;<br />
<br />
FDataset := TSdfDataset.Create(nil);<br />
FDataset.FileName := vConfigurations.ComponentsDBFile;<br />
<br />
// Not necessary with TSdfDataset<br />
// FDataset.TableName := STR_DB_COMPONENTS_TABLE;<br />
// FDataset.PrimaryKey := STR_DB_COMPONENTS_ID;<br />
<br />
// Adds field definitions<br />
FDataset.FieldDefs.Add('ID', ftString);<br />
FDataset.FieldDefs.Add('NAMEEN', ftString);<br />
FDataset.FieldDefs.Add('NAMEPT', ftString);<br />
FDataset.FieldDefs.Add('HEIGHT', ftString);<br />
FDataset.FieldDefs.Add('WIDTH', ftString);<br />
FDataset.FieldDefs.Add('PINS', ftString);<br />
FDataset.FieldDefs.Add('DRAWINGCODE', ftString);<br />
<br />
// Necessary for TSdfDataset<br />
FDataset.Delimiter := ',';<br />
FDataset.FirstLineAsSchema := True;<br />
<br />
FDataset.Active := True;<br />
<br />
// Sets the initial record<br />
CurrentRecNo := 1;<br />
FDataset.First;<br />
end;</syntaxhighlight><br />
<br />
When using TSdfDataset directly be aware that RecNo, although it is implemented, does not work as a way to move through the dataset whether reading or writing records. The standard navigation routines like First, Next, Prior and Last work as expected, so you need to use them rather than RecNo.<br />
If you are used to using absolute record numbers to navigate around a database you can implement your own version of RecNo. Declare a global longint variable called CurrentRecNo which will hold the current RecNo value. Remember that this variable will have the same convention as RecNo, so the first record has number 1 (it is not zero-based). After activating the database initialize the database to the first record with TSdfDataset.First and set CurrentRecNo := 1<br />
<br />
<syntaxhighlight>{@@<br />
Moves to the desired record using TDataset.Next and TDataset.Prior<br />
This avoids using TDataset.RecNo which doesn't navigate reliably in any dataset.<br />
<br />
@param AID Indicates the record number. The first record has number 1<br />
}<br />
procedure TComponentsDatabase.GoToRec(AID: Integer);<br />
begin<br />
// We are before the desired record, move forward<br />
if CurrentRecNo < AID then<br />
begin<br />
while (not FDataset.EOF) and (CurrentRecNo < AID) do<br />
begin<br />
FDataset.Next;<br />
FDataset.CursorPosChanged;<br />
Inc(CurrentRecNo);<br />
end;<br />
end<br />
// We are after the desired record, move back<br />
else if CurrentRecNo > AID then<br />
begin<br />
while (CurrentRecNo >= 1) and (CurrentRecNo > AID) do<br />
begin<br />
FDataset.Prior;<br />
FDataset.CursorPosChanged;<br />
Dec(CurrentRecNo);<br />
end;<br />
end;<br />
end;</syntaxhighlight><br />
<br />
=== Using with data-aware controls ===<br />
<br />
== Lazarus and Advantage Database Server ==<br />
* Please see [[Advantage Database Server]] for details on using Advantage Database Server<br />
<br />
==See also==<br />
* [[Database_field_type]]<br />
* [[Databases]]<br />
* [[Databases in Lazarus]]<br />
* [[Firebird in action]]<br />
* [[How to write in-memory database applications in Lazarus/FPC]]<br />
* [[Lazarus DB Faq]]<br />
* [[Lazarus Tdbf Tutorial]]<br />
* [[MS Access]]<br />
* [[multi-tier_options_with_fpc|Multi-tier options with FPC]]<br />
* [[MySQLDatabases]]<br />
* [[ODBCConn]]<br />
* [[SQLdb Tutorial1]]<br />
* [[SqlDBHowto]]<br />
* [[SQLite]]<br />
* [[tiOPF]] - a free and open source Object Persistence Framework.<br />
* [[Zeos tutorial]]<br />
<br />
==External links==<br />
<br />
* [http://pdo.sourceforge.net Pascal Data Objects] - a database API that worked for both FPC and Delphi and utilises native MySQL libraries for version 4.1 and 5.0 and Firebird SQL 1.5, and 2.0. It's inspired by PHP's PDO class.<br />
* [http://lazaruszeos.blogspot.com Zeos+SQLite Tutorial] - Good tutorial using screenshots and screencasts it explain how to use SQLite and Zeos, spanish (google translate does a good work in translating it to english)<br />
<br />
<br />
[[Category:Databases]]<br />
[[Category:Tutorials]]</div>Mario13https://wiki.freepascal.org/index.php?title=Lazarus_Database_Overview&diff=62549Lazarus Database Overview2012-10-08T15:21:04Z<p>Mario13: /* Lazarus and MSSQL/Sybase */</p>
<hr />
<div>{{Translate}}<br />
<br />
== Overview ==<br />
<br />
This article is an overview of the which databases can work with Lazarus.<br />
<br />
Lazarus supports several databases out of the box (using e.g. the SQLDB framework), however the developer must install the required packages (client libraries) for each one. <br />
<br />
You can access the database through code or by dropping components on a form. The data-aware components represent fields and are connected by setting the DataSource property to point to a TDataSource. The Datasource represents a table and is connected to the database components (examples: ''TPSQLDatabase'', ''TSQLiteDataSet'') by setting the DataSet property. The data-aware components are located on the "Data Controls" tab. The Datasource and the database controls are located on the "Data Access" tab.<br />
<br />
== Lazarus and Interbase / Firebird ==<br />
* Please see [[Firebird_in_action|Firebird in action]] for details on various access methods, which include<br />
# Built-in SQLDB support<br />
# FBLib<br />
# IBX<br />
# PDO<br />
# Zeos<br />
<br />
For a tutorial that leads you through creating a Lazarus GUI for a Firebird database, see:<br />
* [[SQLdb Tutorial1]]<br />
<br />
<br />
== Lazarus and MySQL ==<br />
* Please see [[mysql]] for details on various access methods, which include:<br />
# Built-in SQLDB support<br />
# PDO<br />
# Zeos<br />
<br />
== Lazarus and MSSQL/Sybase ==<br />
You can connect to Microsoft SQL Server databases using<br />
# The built-in SQLdb (recent Lazarus/FPC 2.6.1+): '''TMSSQLConnection''' (MS SQL) and '''TSybaseConnection''' (Sybase ASE)<br />
## On Windows by default it use FreeTDS library '''dblib.dll'''. By modifying FPC file '''dblib.pas''' it could use native library ntwdblib.dll (in this case FPC needs to be recompiled).<br />
## On Linux by default it use '''libsybdb.so''' which is FreeTDS library (for example, in Debian is in package '''libsybd5''').<br />
# Zeos '''TZConnection''' (latest CVS, see links to Zeos elsewhere on this page)<br />
## On Windows you can choose between native library ntwdblib.dll (protocol '''mssql''') or FreeTDS libraries (protocol '''FreeTDS_MsSQL-nnnn''') where nnnn is one of four variants depending on the server version. <br />
## On Linux the only way is with FreeTDS protocols and libraries (you should use '''libsybdb.so''').<br />
# ODBC (MS SQL and Sybase ASE) with SQLdb '''TODBCConnection'''<br />
## On Windows it uses native ODBC Microsoft libraries (like sqlsrv32.dll for SQL server 2000)<br />
## On Linux it uses unixODBC + FreeTDS (packages unixodbc or iodbc, and tdsodbc)<br />
Please see the FPC and Lazarus help files for details on using SQLDB with Sybase ASE and MS SQL Server.<br />
<br />
Note1: In any of the above forms, if you use native Microsoft Libraries (over Windows) it could be possible to connect to remote server with Named Pipes or with TCP/IP with fixed port (like 1433). If you use Wine in Linux only FreeTDS libraries are working, native libraries or Named Pipes will not work (for now). On the other hand, if you use FreeTDS libraries, connecting with Named Pipes is not supported, only TCP/IP connections with fixed port (like 1433) are supported.<br />
<br />
Note2: Lazarus 1.0 was released with FPC 2.6.0 and does not include TMSSQLConnection or TSybaseConnection. If you want these, it might be easiest to download a snapshot of the latest Lazarus built with FPC 2.6.1, optinally installing that in a directory different from your Lazarus 1.0 version. You can use --primary-config-path to set up a separate environment for the Lazarus snapshot (see [[Multiple_Lazarus]])<br />
<br />
== Lazarus and ODBC ==<br />
ODBC is a general database connection standard which is available on Linux, Windows and OSX. You will need an ODBC driver from your database vendor and set up an ODBC "data source" (also known as DSN).<br />
You can use the SQLDB components (TODBCConnection) to connect to an ODBC data soruce.<br />
See [[ODBCConn]] for more details and examples<br />
<br />
== Lazarus and Oracle ==<br />
* Acces methods include:<br />
# Built-in SQLDB support<br />
# Zeos<br />
<br />
== Lazarus and PostgreSQL ==<br />
* Please see [[postgres]] for details on various access methods, which include:<br />
# Built-in SQLdb support. Use component '''TPQConnection''' from palette '''SQLdb'''<br />
# Zeos. Use component '''TZConnection''' with protocol 'postgresql' from palette '''Zeos Access'''<br />
<br />
== Lazarus and SQLite ==<br />
SQLite is an embedded database; the database code can be distributed as a library (.dll/.so/.dylib) with your application to make it self-contained (comparable to Firebird embedded). SQLite is quite popular due to its relative simplicity, speed, small size and cross-platform support.<br />
<br />
Please see the [[SQLite]] page for details on various access methods, which include:<br />
# Built-in SQLDb support<br />
# Zeos<br />
# SQLitePass <br />
# TSQLite3Dataset<br />
<br />
== Lazarus and dBase ==<br />
<br />
[[user:Tonymaro|Tony Maro]]<br />
<br />
You might also want to visit the [[Lazarus Tdbf Tutorial|TDbf Tutorial page]]<br />
<br />
FPC includes a simple database component that is similar in function to the Delphi TTable component called "TDbf" ([http://tdbf.sourceforge.net/ TDbf Website]) that supports a subset of features for dBase files. It is not installed by default, so you will first need to install the Lazarus package from the "lazarus/components/tdbf" directory and rebuild your Lazarus IDE. It will then appear next to the TDatasource in your component palette (Data Access tab).<br />
<br />
The TDbf component has an advantage over other database components in that it doesn't require any sort of runtime database engine. However it's not the best option for large database applications.<br />
<br />
It's very easy to use. Simply drop a TDbf on your form, set the runtime path to the directory that your database files will be in, set the table name, and link it to your TDatasource component.<br />
<br />
Real functionality requires a bit more effort, however. If a table doesn't already exist, you'll need to create it programmatically, unless there's a compatible table designer I'm not familiar with.<br />
Note: Current version of OpenOffice/LibreOffice (3.x) contains OpenOffice Base, which can create dbf files in a somewhat user-friendly way.<br />
<br />
Attempting to open a nonexistent table will generate an error. Tables can be created programmatically through the component after the runtime path and table name are set.<br />
<br />
For instance, to create a table called "dvds" to store your DVD collection you would drop it on your form, set the runtime path, and set the table name to "dvds". The resulting file will be called "dvds.dbf".<br />
<br />
In your code, insert the following:<br />
<br />
<syntaxhighlight>Dbf1.FilePathFull := '/path/to/my/database';<br />
Dbf1.TableName := 'dvds';<br />
With Dbf1.FieldDefs do begin<br />
Add('Name', ftString, 80, True);<br />
Add('Description', ftMemo, 0, False);<br />
Add('Rating', ftString, 5, False);<br />
end;<br />
Dbf1.CreateTable;</syntaxhighlight><br />
<br />
When this code is run, your DVD collection table will be created. After that, all data aware components linked through the TDatasource to this component will allow easy access to the data. <br />
<br />
Adding an index is a little different from your typical TTable. It must be done after the database is open. You use the same method also to rebuild the indices. For instance:<br />
<br />
<syntaxhighlight>Dbf1.Exclusive := True;<br />
Dbf1.Open;<br />
Dbf1.AddIndex('dvdsname','Name',[ixPrimary, ixUnique, ixCaseInsensitive]);<br />
Dbf1.AddIndex('rating.ndx', 'Rating', [ixCaseInsensitive]);<br />
Dbf1.Close;</syntaxhighlight><br />
<br />
The first (primary) index will be a file called "dvdsname.mdx" and the second will be a file named "rating.ndx" so in a multiple table database you must be careful not to use the same file name again.<br />
<br />
Please see [[Lazarus Tdbf Tutorial|TDbf Tutorial page]] for more details, but hopefully this will get those old Delphi programmers up and running with databases in Lazarus!<br />
<br />
===Searching and Displaying a data set===<br />
<br />
[[user:svbfieldview.net|Simon Batty]]<br />
<br />
In this example I wanted to search a database of books for all the titles an author has listed<br />
and then display the list in a memo box<br />
<syntaxhighlight>Dbf1.FilePathFull := '/home/somelocatio/database_location/'; // path to the database directory<br />
Dbf1.TableName := 'books.dbase'; // database file (including extension)<br />
DbF1.Open;<br />
memo1.Clear; // clear the memo box<br />
<br />
Dbf1.FilterOptions := [foCaseInsensitive];<br />
Df1.Filter := 'AU=' + QuotedStr('anauthor'); // AU is the field name containing the authors<br />
<br />
Dbf1.Filtered := true; // This selects the filtered set<br />
Dbf1.First; // moves the the first filtered data<br />
while not dbf1.EOF do // prints the titles that match the author to the memo box<br />
begin<br />
memo1.Append(Dbf1.FieldByName('TI').AsString); // TI is the field name for titles<br />
dbf1.next; // use .next here NOT .findnext!<br />
end;<br />
Dbf1.Close;</syntaxhighlight> <br />
<br />
Note that you can use Ddf1.findfirst to get the first record in the filtered set, then use <br />
Dbf1.next to move though the data. I found that using Dbf1.Findnext just causes the program to hang. <br />
<br />
This database was generated using TurboBD that came with the Kylix 1. I cannot get TurboBD tables to work with Lazarus, however you can download a command line tool from TurboDB's website that allows you to convert TurboDB table to other formats.<br />
<br />
== Using TSdfDataset and TFixedDataset ==<br />
<br />
TSdfDataset and TFixedDataset are two simple datasets which offer a very simple textual storage format. These datasets are very convenient for small databases, because they are fully implemented as an object pascal unit, and thus require no external libraries, and because their textual format allows them to be easely edited with a text editor.<br />
<br />
To start with this formats, a initial database file should be created. The format is very simple, so use a text editor to do this.<br />
<br />
Bellow is a sample database for TSdfDataset. Note that the first line has the names of the fields and that we are using commas as separators:<br />
<br />
<pre>ID,NAMEEN,NAMEPT,HEIGHT,WIDTH,PINS,DRAWINGCODE<br />
1,resistor,resistor,1,1,1,LINE<br />
2,capacitor,capacitor,1,1,1,LINE<br />
3,transistor npn,transistor npn</pre><br />
<br />
And here is an example database for using with TFixedDataset. Each record occupies a fixed amount of space, and if the field is smaller then it, spaces should be used to fill the remaining size.<br />
<br />
<pre>Name = 15 chars; Surname = 15 chars; Tell = 10 chars; e_mail = 20 chars;<br />
Piet Pompies piet@pompies.net</pre><br />
<br />
=== Using the datasets directly ===<br />
<br />
Sometimes it is useful to create the dataset and work with it completely in code, and the following code will do exactly this. Note some peculiarities of TSdfDataset/TFixedDataset:<br />
<br />
* The lines in the database can have a maximum size of about 300. A fix is being researched.<br />
* It is necessary to add the field definitions. Some datasets are able to fill this information alone from the database file<br />
* One should set FirstLineAsSchema to true, to indicate that the first line includes the field names and positions<br />
* The Delimiter property holds the separator for the fields. It will not be possible to use this char in strings in the database. Similarly it will not be possible to have lineendings in the database because they mark the change between records. It's possible to overcome this by substituting the needed comma or line ending with another not often used char, like # for example. So that when showing the data on screen all # chars could be converted to line endings and the inverse when storing data back to the database. The ReplaceString routine is useful here.<br />
<br />
<syntaxhighlight><br />
uses sdfdata, db;<br />
<br />
constructor TComponentsDatabase.Create;<br />
var<br />
FDataset: TSdfDataset;<br />
begin<br />
inherited Create;<br />
<br />
FDataset := TSdfDataset.Create(nil);<br />
FDataset.FileName := vConfigurations.ComponentsDBFile;<br />
<br />
// Not necessary with TSdfDataset<br />
// FDataset.TableName := STR_DB_COMPONENTS_TABLE;<br />
// FDataset.PrimaryKey := STR_DB_COMPONENTS_ID;<br />
<br />
// Adds field definitions<br />
FDataset.FieldDefs.Add('ID', ftString);<br />
FDataset.FieldDefs.Add('NAMEEN', ftString);<br />
FDataset.FieldDefs.Add('NAMEPT', ftString);<br />
FDataset.FieldDefs.Add('HEIGHT', ftString);<br />
FDataset.FieldDefs.Add('WIDTH', ftString);<br />
FDataset.FieldDefs.Add('PINS', ftString);<br />
FDataset.FieldDefs.Add('DRAWINGCODE', ftString);<br />
<br />
// Necessary for TSdfDataset<br />
FDataset.Delimiter := ',';<br />
FDataset.FirstLineAsSchema := True;<br />
<br />
FDataset.Active := True;<br />
<br />
// Sets the initial record<br />
CurrentRecNo := 1;<br />
FDataset.First;<br />
end;</syntaxhighlight><br />
<br />
When using TSdfDataset directly be aware that RecNo, although it is implemented, does not work as a way to move through the dataset whether reading or writing records. The standard navigation routines like First, Next, Prior and Last work as expected, so you need to use them rather than RecNo.<br />
If you are used to using absolute record numbers to navigate around a database you can implement your own version of RecNo. Declare a global longint variable called CurrentRecNo which will hold the current RecNo value. Remember that this variable will have the same convention as RecNo, so the first record has number 1 (it is not zero-based). After activating the database initialize the database to the first record with TSdfDataset.First and set CurrentRecNo := 1<br />
<br />
<syntaxhighlight>{@@<br />
Moves to the desired record using TDataset.Next and TDataset.Prior<br />
This avoids using TDataset.RecNo which doesn't navigate reliably in any dataset.<br />
<br />
@param AID Indicates the record number. The first record has number 1<br />
}<br />
procedure TComponentsDatabase.GoToRec(AID: Integer);<br />
begin<br />
// We are before the desired record, move forward<br />
if CurrentRecNo < AID then<br />
begin<br />
while (not FDataset.EOF) and (CurrentRecNo < AID) do<br />
begin<br />
FDataset.Next;<br />
FDataset.CursorPosChanged;<br />
Inc(CurrentRecNo);<br />
end;<br />
end<br />
// We are after the desired record, move back<br />
else if CurrentRecNo > AID then<br />
begin<br />
while (CurrentRecNo >= 1) and (CurrentRecNo > AID) do<br />
begin<br />
FDataset.Prior;<br />
FDataset.CursorPosChanged;<br />
Dec(CurrentRecNo);<br />
end;<br />
end;<br />
end;</syntaxhighlight><br />
<br />
=== Using with data-aware controls ===<br />
<br />
== Lazarus and Advantage Database Server ==<br />
* Please see [[Advantage Database Server]] for details on using Advantage Database Server<br />
<br />
==See also==<br />
* [[Database_field_type]]<br />
* [[Databases]]<br />
* [[Databases in Lazarus]]<br />
* [[Firebird in action]]<br />
* [[How to write in-memory database applications in Lazarus/FPC]]<br />
* [[Lazarus DB Faq]]<br />
* [[Lazarus Tdbf Tutorial]]<br />
* [[MS Access]]<br />
* [[multi-tier_options_with_fpc|Multi-tier options with FPC]]<br />
* [[MySQLDatabases]]<br />
* [[ODBCConn]]<br />
* [[SQLdb Tutorial1]]<br />
* [[SqlDBHowto]]<br />
* [[SQLite]]<br />
* [[tiOPF]] - a free and open source Object Persistence Framework.<br />
* [[Zeos tutorial]]<br />
<br />
==External links==<br />
<br />
* [http://pdo.sourceforge.net Pascal Data Objects] - a database API that worked for both FPC and Delphi and utilises native MySQL libraries for version 4.1 and 5.0 and Firebird SQL 1.5, and 2.0. It's inspired by PHP's PDO class.<br />
* [http://lazaruszeos.blogspot.com Zeos+SQLite Tutorial] - Good tutorial using screenshots and screencasts it explain how to use SQLite and Zeos, spanish (google translate does a good work in translating it to english)<br />
<br />
<br />
[[Category:Databases]]<br />
[[Category:Tutorials]]</div>Mario13https://wiki.freepascal.org/index.php?title=Lazarus_Database_Overview&diff=62548Lazarus Database Overview2012-10-08T15:20:24Z<p>Mario13: /* Lazarus and MSSQL/Sybase */</p>
<hr />
<div>{{Translate}}<br />
<br />
== Overview ==<br />
<br />
This article is an overview of the which databases can work with Lazarus.<br />
<br />
Lazarus supports several databases out of the box (using e.g. the SQLDB framework), however the developer must install the required packages (client libraries) for each one. <br />
<br />
You can access the database through code or by dropping components on a form. The data-aware components represent fields and are connected by setting the DataSource property to point to a TDataSource. The Datasource represents a table and is connected to the database components (examples: ''TPSQLDatabase'', ''TSQLiteDataSet'') by setting the DataSet property. The data-aware components are located on the "Data Controls" tab. The Datasource and the database controls are located on the "Data Access" tab.<br />
<br />
== Lazarus and Interbase / Firebird ==<br />
* Please see [[Firebird_in_action|Firebird in action]] for details on various access methods, which include<br />
# Built-in SQLDB support<br />
# FBLib<br />
# IBX<br />
# PDO<br />
# Zeos<br />
<br />
For a tutorial that leads you through creating a Lazarus GUI for a Firebird database, see:<br />
* [[SQLdb Tutorial1]]<br />
<br />
<br />
== Lazarus and MySQL ==<br />
* Please see [[mysql]] for details on various access methods, which include:<br />
# Built-in SQLDB support<br />
# PDO<br />
# Zeos<br />
<br />
== Lazarus and MSSQL/Sybase ==<br />
You can connect to Microsoft SQL Server databases using<br />
# The built-in SQLdb (recent Lazarus/FPC 2.6.1+): '''TMSSQLConnection''' (MS SQL) and '''TSybaseConnection''' (Sybase ASE)<br />
## On Windows by default it use FreeTDS library '''dblib.dll'''. By modifying FPC file '''dblib.pas''' it could use native library ntwdblib.dll (in this case FPC needs to be recompiled).<br />
## On Linux by default it use '''libsybdb.so''' which is FreeTDS library (for example, in Debian is in package '''libsybd5''').<br />
# Zeos '''TZConnection''' (latest CVS, see links to Zeos elsewhere on this page)<br />
## On Windows you can choose between native library ntwdblib.dll (protocol '''mssql''') or FreeTDS libraries (protocol '''FreeTDS_MsSQL-nnnn''') where nnnn is one of four variants depending on the server version. <br />
## On Linux the only way is with FreeTDS protocols and libraries (you should use '''libsybdb.so''').<br />
# ODBC (MS SQL and Sybase ASE) with SQLdb '''TODBCConnection'''<br />
## On Windows it uses native ODBC Microsoft libraries (like sqlsrv32.dll for SQL server 2000)<br />
## On Linux it uses unixODBC + FreeTDS (packages unixodbc or iodbc, and tdsodbc)<br />
Please see the FPC and Lazarus help files for details on using SQLDB with Sybase ASE and MS SQL Server.<br />
<br />
Note1: In any of the above forms, if you use native Microsoft Libraries (over Windows) it could be possible to connect to remote server with Named Pipes or with TCP/IP with fixed port (like 1433). If you use Wine in Linux only FreeTDS libraries is working, native libraries or Named Pipes will not work (for now). On the other hand, if you use FreeTDS libraries, connecting with Named Pipes is not supported, only TCP/IP connections with fixed port (like 1433) are supported.<br />
<br />
Note2: Lazarus 1.0 was released with FPC 2.6.0 and does not include TMSSQLConnection or TSybaseConnection. If you want these, it might be easiest to download a snapshot of the latest Lazarus built with FPC 2.6.1, optinally installing that in a directory different from your Lazarus 1.0 version. You can use --primary-config-path to set up a separate environment for the Lazarus snapshot (see [[Multiple_Lazarus]])<br />
<br />
== Lazarus and ODBC ==<br />
ODBC is a general database connection standard which is available on Linux, Windows and OSX. You will need an ODBC driver from your database vendor and set up an ODBC "data source" (also known as DSN).<br />
You can use the SQLDB components (TODBCConnection) to connect to an ODBC data soruce.<br />
See [[ODBCConn]] for more details and examples<br />
<br />
== Lazarus and Oracle ==<br />
* Acces methods include:<br />
# Built-in SQLDB support<br />
# Zeos<br />
<br />
== Lazarus and PostgreSQL ==<br />
* Please see [[postgres]] for details on various access methods, which include:<br />
# Built-in SQLdb support. Use component '''TPQConnection''' from palette '''SQLdb'''<br />
# Zeos. Use component '''TZConnection''' with protocol 'postgresql' from palette '''Zeos Access'''<br />
<br />
== Lazarus and SQLite ==<br />
SQLite is an embedded database; the database code can be distributed as a library (.dll/.so/.dylib) with your application to make it self-contained (comparable to Firebird embedded). SQLite is quite popular due to its relative simplicity, speed, small size and cross-platform support.<br />
<br />
Please see the [[SQLite]] page for details on various access methods, which include:<br />
# Built-in SQLDb support<br />
# Zeos<br />
# SQLitePass <br />
# TSQLite3Dataset<br />
<br />
== Lazarus and dBase ==<br />
<br />
[[user:Tonymaro|Tony Maro]]<br />
<br />
You might also want to visit the [[Lazarus Tdbf Tutorial|TDbf Tutorial page]]<br />
<br />
FPC includes a simple database component that is similar in function to the Delphi TTable component called "TDbf" ([http://tdbf.sourceforge.net/ TDbf Website]) that supports a subset of features for dBase files. It is not installed by default, so you will first need to install the Lazarus package from the "lazarus/components/tdbf" directory and rebuild your Lazarus IDE. It will then appear next to the TDatasource in your component palette (Data Access tab).<br />
<br />
The TDbf component has an advantage over other database components in that it doesn't require any sort of runtime database engine. However it's not the best option for large database applications.<br />
<br />
It's very easy to use. Simply drop a TDbf on your form, set the runtime path to the directory that your database files will be in, set the table name, and link it to your TDatasource component.<br />
<br />
Real functionality requires a bit more effort, however. If a table doesn't already exist, you'll need to create it programmatically, unless there's a compatible table designer I'm not familiar with.<br />
Note: Current version of OpenOffice/LibreOffice (3.x) contains OpenOffice Base, which can create dbf files in a somewhat user-friendly way.<br />
<br />
Attempting to open a nonexistent table will generate an error. Tables can be created programmatically through the component after the runtime path and table name are set.<br />
<br />
For instance, to create a table called "dvds" to store your DVD collection you would drop it on your form, set the runtime path, and set the table name to "dvds". The resulting file will be called "dvds.dbf".<br />
<br />
In your code, insert the following:<br />
<br />
<syntaxhighlight>Dbf1.FilePathFull := '/path/to/my/database';<br />
Dbf1.TableName := 'dvds';<br />
With Dbf1.FieldDefs do begin<br />
Add('Name', ftString, 80, True);<br />
Add('Description', ftMemo, 0, False);<br />
Add('Rating', ftString, 5, False);<br />
end;<br />
Dbf1.CreateTable;</syntaxhighlight><br />
<br />
When this code is run, your DVD collection table will be created. After that, all data aware components linked through the TDatasource to this component will allow easy access to the data. <br />
<br />
Adding an index is a little different from your typical TTable. It must be done after the database is open. You use the same method also to rebuild the indices. For instance:<br />
<br />
<syntaxhighlight>Dbf1.Exclusive := True;<br />
Dbf1.Open;<br />
Dbf1.AddIndex('dvdsname','Name',[ixPrimary, ixUnique, ixCaseInsensitive]);<br />
Dbf1.AddIndex('rating.ndx', 'Rating', [ixCaseInsensitive]);<br />
Dbf1.Close;</syntaxhighlight><br />
<br />
The first (primary) index will be a file called "dvdsname.mdx" and the second will be a file named "rating.ndx" so in a multiple table database you must be careful not to use the same file name again.<br />
<br />
Please see [[Lazarus Tdbf Tutorial|TDbf Tutorial page]] for more details, but hopefully this will get those old Delphi programmers up and running with databases in Lazarus!<br />
<br />
===Searching and Displaying a data set===<br />
<br />
[[user:svbfieldview.net|Simon Batty]]<br />
<br />
In this example I wanted to search a database of books for all the titles an author has listed<br />
and then display the list in a memo box<br />
<syntaxhighlight>Dbf1.FilePathFull := '/home/somelocatio/database_location/'; // path to the database directory<br />
Dbf1.TableName := 'books.dbase'; // database file (including extension)<br />
DbF1.Open;<br />
memo1.Clear; // clear the memo box<br />
<br />
Dbf1.FilterOptions := [foCaseInsensitive];<br />
Df1.Filter := 'AU=' + QuotedStr('anauthor'); // AU is the field name containing the authors<br />
<br />
Dbf1.Filtered := true; // This selects the filtered set<br />
Dbf1.First; // moves the the first filtered data<br />
while not dbf1.EOF do // prints the titles that match the author to the memo box<br />
begin<br />
memo1.Append(Dbf1.FieldByName('TI').AsString); // TI is the field name for titles<br />
dbf1.next; // use .next here NOT .findnext!<br />
end;<br />
Dbf1.Close;</syntaxhighlight> <br />
<br />
Note that you can use Ddf1.findfirst to get the first record in the filtered set, then use <br />
Dbf1.next to move though the data. I found that using Dbf1.Findnext just causes the program to hang. <br />
<br />
This database was generated using TurboBD that came with the Kylix 1. I cannot get TurboBD tables to work with Lazarus, however you can download a command line tool from TurboDB's website that allows you to convert TurboDB table to other formats.<br />
<br />
== Using TSdfDataset and TFixedDataset ==<br />
<br />
TSdfDataset and TFixedDataset are two simple datasets which offer a very simple textual storage format. These datasets are very convenient for small databases, because they are fully implemented as an object pascal unit, and thus require no external libraries, and because their textual format allows them to be easely edited with a text editor.<br />
<br />
To start with this formats, a initial database file should be created. The format is very simple, so use a text editor to do this.<br />
<br />
Bellow is a sample database for TSdfDataset. Note that the first line has the names of the fields and that we are using commas as separators:<br />
<br />
<pre>ID,NAMEEN,NAMEPT,HEIGHT,WIDTH,PINS,DRAWINGCODE<br />
1,resistor,resistor,1,1,1,LINE<br />
2,capacitor,capacitor,1,1,1,LINE<br />
3,transistor npn,transistor npn</pre><br />
<br />
And here is an example database for using with TFixedDataset. Each record occupies a fixed amount of space, and if the field is smaller then it, spaces should be used to fill the remaining size.<br />
<br />
<pre>Name = 15 chars; Surname = 15 chars; Tell = 10 chars; e_mail = 20 chars;<br />
Piet Pompies piet@pompies.net</pre><br />
<br />
=== Using the datasets directly ===<br />
<br />
Sometimes it is useful to create the dataset and work with it completely in code, and the following code will do exactly this. Note some peculiarities of TSdfDataset/TFixedDataset:<br />
<br />
* The lines in the database can have a maximum size of about 300. A fix is being researched.<br />
* It is necessary to add the field definitions. Some datasets are able to fill this information alone from the database file<br />
* One should set FirstLineAsSchema to true, to indicate that the first line includes the field names and positions<br />
* The Delimiter property holds the separator for the fields. It will not be possible to use this char in strings in the database. Similarly it will not be possible to have lineendings in the database because they mark the change between records. It's possible to overcome this by substituting the needed comma or line ending with another not often used char, like # for example. So that when showing the data on screen all # chars could be converted to line endings and the inverse when storing data back to the database. The ReplaceString routine is useful here.<br />
<br />
<syntaxhighlight><br />
uses sdfdata, db;<br />
<br />
constructor TComponentsDatabase.Create;<br />
var<br />
FDataset: TSdfDataset;<br />
begin<br />
inherited Create;<br />
<br />
FDataset := TSdfDataset.Create(nil);<br />
FDataset.FileName := vConfigurations.ComponentsDBFile;<br />
<br />
// Not necessary with TSdfDataset<br />
// FDataset.TableName := STR_DB_COMPONENTS_TABLE;<br />
// FDataset.PrimaryKey := STR_DB_COMPONENTS_ID;<br />
<br />
// Adds field definitions<br />
FDataset.FieldDefs.Add('ID', ftString);<br />
FDataset.FieldDefs.Add('NAMEEN', ftString);<br />
FDataset.FieldDefs.Add('NAMEPT', ftString);<br />
FDataset.FieldDefs.Add('HEIGHT', ftString);<br />
FDataset.FieldDefs.Add('WIDTH', ftString);<br />
FDataset.FieldDefs.Add('PINS', ftString);<br />
FDataset.FieldDefs.Add('DRAWINGCODE', ftString);<br />
<br />
// Necessary for TSdfDataset<br />
FDataset.Delimiter := ',';<br />
FDataset.FirstLineAsSchema := True;<br />
<br />
FDataset.Active := True;<br />
<br />
// Sets the initial record<br />
CurrentRecNo := 1;<br />
FDataset.First;<br />
end;</syntaxhighlight><br />
<br />
When using TSdfDataset directly be aware that RecNo, although it is implemented, does not work as a way to move through the dataset whether reading or writing records. The standard navigation routines like First, Next, Prior and Last work as expected, so you need to use them rather than RecNo.<br />
If you are used to using absolute record numbers to navigate around a database you can implement your own version of RecNo. Declare a global longint variable called CurrentRecNo which will hold the current RecNo value. Remember that this variable will have the same convention as RecNo, so the first record has number 1 (it is not zero-based). After activating the database initialize the database to the first record with TSdfDataset.First and set CurrentRecNo := 1<br />
<br />
<syntaxhighlight>{@@<br />
Moves to the desired record using TDataset.Next and TDataset.Prior<br />
This avoids using TDataset.RecNo which doesn't navigate reliably in any dataset.<br />
<br />
@param AID Indicates the record number. The first record has number 1<br />
}<br />
procedure TComponentsDatabase.GoToRec(AID: Integer);<br />
begin<br />
// We are before the desired record, move forward<br />
if CurrentRecNo < AID then<br />
begin<br />
while (not FDataset.EOF) and (CurrentRecNo < AID) do<br />
begin<br />
FDataset.Next;<br />
FDataset.CursorPosChanged;<br />
Inc(CurrentRecNo);<br />
end;<br />
end<br />
// We are after the desired record, move back<br />
else if CurrentRecNo > AID then<br />
begin<br />
while (CurrentRecNo >= 1) and (CurrentRecNo > AID) do<br />
begin<br />
FDataset.Prior;<br />
FDataset.CursorPosChanged;<br />
Dec(CurrentRecNo);<br />
end;<br />
end;<br />
end;</syntaxhighlight><br />
<br />
=== Using with data-aware controls ===<br />
<br />
== Lazarus and Advantage Database Server ==<br />
* Please see [[Advantage Database Server]] for details on using Advantage Database Server<br />
<br />
==See also==<br />
* [[Database_field_type]]<br />
* [[Databases]]<br />
* [[Databases in Lazarus]]<br />
* [[Firebird in action]]<br />
* [[How to write in-memory database applications in Lazarus/FPC]]<br />
* [[Lazarus DB Faq]]<br />
* [[Lazarus Tdbf Tutorial]]<br />
* [[MS Access]]<br />
* [[multi-tier_options_with_fpc|Multi-tier options with FPC]]<br />
* [[MySQLDatabases]]<br />
* [[ODBCConn]]<br />
* [[SQLdb Tutorial1]]<br />
* [[SqlDBHowto]]<br />
* [[SQLite]]<br />
* [[tiOPF]] - a free and open source Object Persistence Framework.<br />
* [[Zeos tutorial]]<br />
<br />
==External links==<br />
<br />
* [http://pdo.sourceforge.net Pascal Data Objects] - a database API that worked for both FPC and Delphi and utilises native MySQL libraries for version 4.1 and 5.0 and Firebird SQL 1.5, and 2.0. It's inspired by PHP's PDO class.<br />
* [http://lazaruszeos.blogspot.com Zeos+SQLite Tutorial] - Good tutorial using screenshots and screencasts it explain how to use SQLite and Zeos, spanish (google translate does a good work in translating it to english)<br />
<br />
<br />
[[Category:Databases]]<br />
[[Category:Tutorials]]</div>Mario13https://wiki.freepascal.org/index.php?title=Lazarus_Database_Overview&diff=62547Lazarus Database Overview2012-10-08T15:13:11Z<p>Mario13: /* Lazarus and MSSQL/Sybase */</p>
<hr />
<div>{{Translate}}<br />
<br />
== Overview ==<br />
<br />
This article is an overview of the which databases can work with Lazarus.<br />
<br />
Lazarus supports several databases out of the box (using e.g. the SQLDB framework), however the developer must install the required packages (client libraries) for each one. <br />
<br />
You can access the database through code or by dropping components on a form. The data-aware components represent fields and are connected by setting the DataSource property to point to a TDataSource. The Datasource represents a table and is connected to the database components (examples: ''TPSQLDatabase'', ''TSQLiteDataSet'') by setting the DataSet property. The data-aware components are located on the "Data Controls" tab. The Datasource and the database controls are located on the "Data Access" tab.<br />
<br />
== Lazarus and Interbase / Firebird ==<br />
* Please see [[Firebird_in_action|Firebird in action]] for details on various access methods, which include<br />
# Built-in SQLDB support<br />
# FBLib<br />
# IBX<br />
# PDO<br />
# Zeos<br />
<br />
For a tutorial that leads you through creating a Lazarus GUI for a Firebird database, see:<br />
* [[SQLdb Tutorial1]]<br />
<br />
<br />
== Lazarus and MySQL ==<br />
* Please see [[mysql]] for details on various access methods, which include:<br />
# Built-in SQLDB support<br />
# PDO<br />
# Zeos<br />
<br />
== Lazarus and MSSQL/Sybase ==<br />
You can connect to Microsoft SQL Server databases using<br />
# The built-in SQLdb (recent Lazarus/FPC 2.6.1+): '''TMSSQLConnection''' (MS SQL) and '''TSybaseConnection''' (Sybase ASE)<br />
## On Windows by default it use FreeTDS library '''dblib.dll'''. By modifying FPC file '''dblib.pas''' it could use native library ntwdblib.dll (in this case FPC needs to be recompiled).<br />
## On Linux by default it use '''libsybdb.so''' which is FreeTDS library (for example, in Debian is in package '''libsybd5''').<br />
# Zeos '''TZConnection''' (latest CVS, see links to Zeos elsewhere on this page)<br />
## On Windows you can choose between native library ntwdblib.dll (protocol '''mssql''') or FreeTDS libraries (protocol '''FreeTDS_MsSQL-nnnn''') where nnnn is one of four variants depending on the server version. <br />
## On Linux the only way is with FreeTDS protocols and libraries (you should use '''libsybdb.so''').<br />
# ODBC (MS SQL and Sybase ASE) with SQLdb '''TODBCConnection'''<br />
## On Windows it uses native ODBC Microsoft libraries (like sqlsrv32.dll for SQL server 2000)<br />
## On Linux it uses unixODBC + FreeTDS (packages unixodbc or iodbc, and tdsodbc)<br />
Please see the FPC and Lazarus help files for details on using SQLDB with Sybase ASE and MS SQL Server.<br />
<br />
Note1: In any of the above forms, if you use native Microsoft Libraries (over Windows) it could be possible to connect to remote server with Named Pipes or with TCP/IP with fixed port (like 1433). If you use native libraries over Wine in Linux only TCP/IP is working, Named Pipes will not work (for now). On the other hand, if you use FreeTDS libraries, connecting with Named Pipes is not supported, only TCP/IP connections with fixed port (like 1433) are supported.<br />
<br />
Note2: Lazarus 1.0 was released with FPC 2.6.0 and does not include TMSSQLConnection or TSybaseConnection. If you want these, it might be easiest to download a snapshot of the latest Lazarus built with FPC 2.6.1, optinally installing that in a directory different from your Lazarus 1.0 version. You can use --primary-config-path to set up a separate environment for the Lazarus snapshot (see [[Multiple_Lazarus]])<br />
<br />
== Lazarus and ODBC ==<br />
ODBC is a general database connection standard which is available on Linux, Windows and OSX. You will need an ODBC driver from your database vendor and set up an ODBC "data source" (also known as DSN).<br />
You can use the SQLDB components (TODBCConnection) to connect to an ODBC data soruce.<br />
See [[ODBCConn]] for more details and examples<br />
<br />
== Lazarus and Oracle ==<br />
* Acces methods include:<br />
# Built-in SQLDB support<br />
# Zeos<br />
<br />
== Lazarus and PostgreSQL ==<br />
* Please see [[postgres]] for details on various access methods, which include:<br />
# Built-in SQLdb support. Use component '''TPQConnection''' from palette '''SQLdb'''<br />
# Zeos. Use component '''TZConnection''' with protocol 'postgresql' from palette '''Zeos Access'''<br />
<br />
== Lazarus and SQLite ==<br />
SQLite is an embedded database; the database code can be distributed as a library (.dll/.so/.dylib) with your application to make it self-contained (comparable to Firebird embedded). SQLite is quite popular due to its relative simplicity, speed, small size and cross-platform support.<br />
<br />
Please see the [[SQLite]] page for details on various access methods, which include:<br />
# Built-in SQLDb support<br />
# Zeos<br />
# SQLitePass <br />
# TSQLite3Dataset<br />
<br />
== Lazarus and dBase ==<br />
<br />
[[user:Tonymaro|Tony Maro]]<br />
<br />
You might also want to visit the [[Lazarus Tdbf Tutorial|TDbf Tutorial page]]<br />
<br />
FPC includes a simple database component that is similar in function to the Delphi TTable component called "TDbf" ([http://tdbf.sourceforge.net/ TDbf Website]) that supports a subset of features for dBase files. It is not installed by default, so you will first need to install the Lazarus package from the "lazarus/components/tdbf" directory and rebuild your Lazarus IDE. It will then appear next to the TDatasource in your component palette (Data Access tab).<br />
<br />
The TDbf component has an advantage over other database components in that it doesn't require any sort of runtime database engine. However it's not the best option for large database applications.<br />
<br />
It's very easy to use. Simply drop a TDbf on your form, set the runtime path to the directory that your database files will be in, set the table name, and link it to your TDatasource component.<br />
<br />
Real functionality requires a bit more effort, however. If a table doesn't already exist, you'll need to create it programmatically, unless there's a compatible table designer I'm not familiar with.<br />
Note: Current version of OpenOffice/LibreOffice (3.x) contains OpenOffice Base, which can create dbf files in a somewhat user-friendly way.<br />
<br />
Attempting to open a nonexistent table will generate an error. Tables can be created programmatically through the component after the runtime path and table name are set.<br />
<br />
For instance, to create a table called "dvds" to store your DVD collection you would drop it on your form, set the runtime path, and set the table name to "dvds". The resulting file will be called "dvds.dbf".<br />
<br />
In your code, insert the following:<br />
<br />
<syntaxhighlight>Dbf1.FilePathFull := '/path/to/my/database';<br />
Dbf1.TableName := 'dvds';<br />
With Dbf1.FieldDefs do begin<br />
Add('Name', ftString, 80, True);<br />
Add('Description', ftMemo, 0, False);<br />
Add('Rating', ftString, 5, False);<br />
end;<br />
Dbf1.CreateTable;</syntaxhighlight><br />
<br />
When this code is run, your DVD collection table will be created. After that, all data aware components linked through the TDatasource to this component will allow easy access to the data. <br />
<br />
Adding an index is a little different from your typical TTable. It must be done after the database is open. You use the same method also to rebuild the indices. For instance:<br />
<br />
<syntaxhighlight>Dbf1.Exclusive := True;<br />
Dbf1.Open;<br />
Dbf1.AddIndex('dvdsname','Name',[ixPrimary, ixUnique, ixCaseInsensitive]);<br />
Dbf1.AddIndex('rating.ndx', 'Rating', [ixCaseInsensitive]);<br />
Dbf1.Close;</syntaxhighlight><br />
<br />
The first (primary) index will be a file called "dvdsname.mdx" and the second will be a file named "rating.ndx" so in a multiple table database you must be careful not to use the same file name again.<br />
<br />
Please see [[Lazarus Tdbf Tutorial|TDbf Tutorial page]] for more details, but hopefully this will get those old Delphi programmers up and running with databases in Lazarus!<br />
<br />
===Searching and Displaying a data set===<br />
<br />
[[user:svbfieldview.net|Simon Batty]]<br />
<br />
In this example I wanted to search a database of books for all the titles an author has listed<br />
and then display the list in a memo box<br />
<syntaxhighlight>Dbf1.FilePathFull := '/home/somelocatio/database_location/'; // path to the database directory<br />
Dbf1.TableName := 'books.dbase'; // database file (including extension)<br />
DbF1.Open;<br />
memo1.Clear; // clear the memo box<br />
<br />
Dbf1.FilterOptions := [foCaseInsensitive];<br />
Df1.Filter := 'AU=' + QuotedStr('anauthor'); // AU is the field name containing the authors<br />
<br />
Dbf1.Filtered := true; // This selects the filtered set<br />
Dbf1.First; // moves the the first filtered data<br />
while not dbf1.EOF do // prints the titles that match the author to the memo box<br />
begin<br />
memo1.Append(Dbf1.FieldByName('TI').AsString); // TI is the field name for titles<br />
dbf1.next; // use .next here NOT .findnext!<br />
end;<br />
Dbf1.Close;</syntaxhighlight> <br />
<br />
Note that you can use Ddf1.findfirst to get the first record in the filtered set, then use <br />
Dbf1.next to move though the data. I found that using Dbf1.Findnext just causes the program to hang. <br />
<br />
This database was generated using TurboBD that came with the Kylix 1. I cannot get TurboBD tables to work with Lazarus, however you can download a command line tool from TurboDB's website that allows you to convert TurboDB table to other formats.<br />
<br />
== Using TSdfDataset and TFixedDataset ==<br />
<br />
TSdfDataset and TFixedDataset are two simple datasets which offer a very simple textual storage format. These datasets are very convenient for small databases, because they are fully implemented as an object pascal unit, and thus require no external libraries, and because their textual format allows them to be easely edited with a text editor.<br />
<br />
To start with this formats, a initial database file should be created. The format is very simple, so use a text editor to do this.<br />
<br />
Bellow is a sample database for TSdfDataset. Note that the first line has the names of the fields and that we are using commas as separators:<br />
<br />
<pre>ID,NAMEEN,NAMEPT,HEIGHT,WIDTH,PINS,DRAWINGCODE<br />
1,resistor,resistor,1,1,1,LINE<br />
2,capacitor,capacitor,1,1,1,LINE<br />
3,transistor npn,transistor npn</pre><br />
<br />
And here is an example database for using with TFixedDataset. Each record occupies a fixed amount of space, and if the field is smaller then it, spaces should be used to fill the remaining size.<br />
<br />
<pre>Name = 15 chars; Surname = 15 chars; Tell = 10 chars; e_mail = 20 chars;<br />
Piet Pompies piet@pompies.net</pre><br />
<br />
=== Using the datasets directly ===<br />
<br />
Sometimes it is useful to create the dataset and work with it completely in code, and the following code will do exactly this. Note some peculiarities of TSdfDataset/TFixedDataset:<br />
<br />
* The lines in the database can have a maximum size of about 300. A fix is being researched.<br />
* It is necessary to add the field definitions. Some datasets are able to fill this information alone from the database file<br />
* One should set FirstLineAsSchema to true, to indicate that the first line includes the field names and positions<br />
* The Delimiter property holds the separator for the fields. It will not be possible to use this char in strings in the database. Similarly it will not be possible to have lineendings in the database because they mark the change between records. It's possible to overcome this by substituting the needed comma or line ending with another not often used char, like # for example. So that when showing the data on screen all # chars could be converted to line endings and the inverse when storing data back to the database. The ReplaceString routine is useful here.<br />
<br />
<syntaxhighlight><br />
uses sdfdata, db;<br />
<br />
constructor TComponentsDatabase.Create;<br />
var<br />
FDataset: TSdfDataset;<br />
begin<br />
inherited Create;<br />
<br />
FDataset := TSdfDataset.Create(nil);<br />
FDataset.FileName := vConfigurations.ComponentsDBFile;<br />
<br />
// Not necessary with TSdfDataset<br />
// FDataset.TableName := STR_DB_COMPONENTS_TABLE;<br />
// FDataset.PrimaryKey := STR_DB_COMPONENTS_ID;<br />
<br />
// Adds field definitions<br />
FDataset.FieldDefs.Add('ID', ftString);<br />
FDataset.FieldDefs.Add('NAMEEN', ftString);<br />
FDataset.FieldDefs.Add('NAMEPT', ftString);<br />
FDataset.FieldDefs.Add('HEIGHT', ftString);<br />
FDataset.FieldDefs.Add('WIDTH', ftString);<br />
FDataset.FieldDefs.Add('PINS', ftString);<br />
FDataset.FieldDefs.Add('DRAWINGCODE', ftString);<br />
<br />
// Necessary for TSdfDataset<br />
FDataset.Delimiter := ',';<br />
FDataset.FirstLineAsSchema := True;<br />
<br />
FDataset.Active := True;<br />
<br />
// Sets the initial record<br />
CurrentRecNo := 1;<br />
FDataset.First;<br />
end;</syntaxhighlight><br />
<br />
When using TSdfDataset directly be aware that RecNo, although it is implemented, does not work as a way to move through the dataset whether reading or writing records. The standard navigation routines like First, Next, Prior and Last work as expected, so you need to use them rather than RecNo.<br />
If you are used to using absolute record numbers to navigate around a database you can implement your own version of RecNo. Declare a global longint variable called CurrentRecNo which will hold the current RecNo value. Remember that this variable will have the same convention as RecNo, so the first record has number 1 (it is not zero-based). After activating the database initialize the database to the first record with TSdfDataset.First and set CurrentRecNo := 1<br />
<br />
<syntaxhighlight>{@@<br />
Moves to the desired record using TDataset.Next and TDataset.Prior<br />
This avoids using TDataset.RecNo which doesn't navigate reliably in any dataset.<br />
<br />
@param AID Indicates the record number. The first record has number 1<br />
}<br />
procedure TComponentsDatabase.GoToRec(AID: Integer);<br />
begin<br />
// We are before the desired record, move forward<br />
if CurrentRecNo < AID then<br />
begin<br />
while (not FDataset.EOF) and (CurrentRecNo < AID) do<br />
begin<br />
FDataset.Next;<br />
FDataset.CursorPosChanged;<br />
Inc(CurrentRecNo);<br />
end;<br />
end<br />
// We are after the desired record, move back<br />
else if CurrentRecNo > AID then<br />
begin<br />
while (CurrentRecNo >= 1) and (CurrentRecNo > AID) do<br />
begin<br />
FDataset.Prior;<br />
FDataset.CursorPosChanged;<br />
Dec(CurrentRecNo);<br />
end;<br />
end;<br />
end;</syntaxhighlight><br />
<br />
=== Using with data-aware controls ===<br />
<br />
== Lazarus and Advantage Database Server ==<br />
* Please see [[Advantage Database Server]] for details on using Advantage Database Server<br />
<br />
==See also==<br />
* [[Database_field_type]]<br />
* [[Databases]]<br />
* [[Databases in Lazarus]]<br />
* [[Firebird in action]]<br />
* [[How to write in-memory database applications in Lazarus/FPC]]<br />
* [[Lazarus DB Faq]]<br />
* [[Lazarus Tdbf Tutorial]]<br />
* [[MS Access]]<br />
* [[multi-tier_options_with_fpc|Multi-tier options with FPC]]<br />
* [[MySQLDatabases]]<br />
* [[ODBCConn]]<br />
* [[SQLdb Tutorial1]]<br />
* [[SqlDBHowto]]<br />
* [[SQLite]]<br />
* [[tiOPF]] - a free and open source Object Persistence Framework.<br />
* [[Zeos tutorial]]<br />
<br />
==External links==<br />
<br />
* [http://pdo.sourceforge.net Pascal Data Objects] - a database API that worked for both FPC and Delphi and utilises native MySQL libraries for version 4.1 and 5.0 and Firebird SQL 1.5, and 2.0. It's inspired by PHP's PDO class.<br />
* [http://lazaruszeos.blogspot.com Zeos+SQLite Tutorial] - Good tutorial using screenshots and screencasts it explain how to use SQLite and Zeos, spanish (google translate does a good work in translating it to english)<br />
<br />
<br />
[[Category:Databases]]<br />
[[Category:Tutorials]]</div>Mario13https://wiki.freepascal.org/index.php?title=Lazarus_Database_Overview&diff=62546Lazarus Database Overview2012-10-08T15:12:10Z<p>Mario13: /* Lazarus and MSSQL/Sybase */</p>
<hr />
<div>{{Translate}}<br />
<br />
== Overview ==<br />
<br />
This article is an overview of the which databases can work with Lazarus.<br />
<br />
Lazarus supports several databases out of the box (using e.g. the SQLDB framework), however the developer must install the required packages (client libraries) for each one. <br />
<br />
You can access the database through code or by dropping components on a form. The data-aware components represent fields and are connected by setting the DataSource property to point to a TDataSource. The Datasource represents a table and is connected to the database components (examples: ''TPSQLDatabase'', ''TSQLiteDataSet'') by setting the DataSet property. The data-aware components are located on the "Data Controls" tab. The Datasource and the database controls are located on the "Data Access" tab.<br />
<br />
== Lazarus and Interbase / Firebird ==<br />
* Please see [[Firebird_in_action|Firebird in action]] for details on various access methods, which include<br />
# Built-in SQLDB support<br />
# FBLib<br />
# IBX<br />
# PDO<br />
# Zeos<br />
<br />
For a tutorial that leads you through creating a Lazarus GUI for a Firebird database, see:<br />
* [[SQLdb Tutorial1]]<br />
<br />
<br />
== Lazarus and MySQL ==<br />
* Please see [[mysql]] for details on various access methods, which include:<br />
# Built-in SQLDB support<br />
# PDO<br />
# Zeos<br />
<br />
== Lazarus and MSSQL/Sybase ==<br />
You can connect to Microsoft SQL Server databases using<br />
# The built-in SQLdb (recent Lazarus/FPC 2.6.1+): TMSSQLConnection (MS SQL) and TSybaseConnection (Sybase ASE)<br />
## On Windows by default it use FreeTDS library '''dblib.dll'''. By modifying FPC file '''dblib.pas''' it could use native library ntwdblib.dll (in this case FPC needs to be recompiled).<br />
## On Linux by default it use '''libsybdb.so''' which is FreeTDS library (for example, in Debian is in package '''libsybd5''').<br />
# Zeos (latest CVS, see links to Zeos elsewhere on this page)<br />
## On Windows you can choose between native library ntwdblib.dll (protocol '''mssql''') or FreeTDS libraries (protocol '''FreeTDS_MsSQL-nnnn''') where nnnn is one of four variants depending on the server version. <br />
## On Linux the only way is with FreeTDS protocols and libraries (you should use '''libsybdb.so''').<br />
# ODBC (MS SQL and Sybase ASE) with SQLdb TODBCConnection<br />
## On Windows it uses native ODBC Microsoft libraries (like sqlsrv32.dll for SQL server 2000)<br />
## On Linux it uses unixODBC + FreeTDS (packages unixodbc or iodbc, and tdsodbc)<br />
Please see the FPC and Lazarus help files for details on using SQLDB with Sybase ASE and MS SQL Server.<br />
<br />
Note1: In any of the above forms, if you use native Microsoft Libraries (over Windows) it could be possible to connect to remote server with Named Pipes or with TCP/IP with fixed port (like 1433). If you use native libraries over Wine in Linux only TCP/IP is working, Named Pipes will not work (for now). On the other hand, if you use FreeTDS libraries, connecting with Named Pipes is not supported, only TCP/IP connections with fixed port (like 1433) are supported.<br />
<br />
Note2: Lazarus 1.0 was released with FPC 2.6.0 and does not include TMSSQLConnection or TSybaseConnection. If you want these, it might be easiest to download a snapshot of the latest Lazarus built with FPC 2.6.1, optinally installing that in a directory different from your Lazarus 1.0 version. You can use --primary-config-path to set up a separate environment for the Lazarus snapshot (see [[Multiple_Lazarus]])<br />
<br />
== Lazarus and ODBC ==<br />
ODBC is a general database connection standard which is available on Linux, Windows and OSX. You will need an ODBC driver from your database vendor and set up an ODBC "data source" (also known as DSN).<br />
You can use the SQLDB components (TODBCConnection) to connect to an ODBC data soruce.<br />
See [[ODBCConn]] for more details and examples<br />
<br />
== Lazarus and Oracle ==<br />
* Acces methods include:<br />
# Built-in SQLDB support<br />
# Zeos<br />
<br />
== Lazarus and PostgreSQL ==<br />
* Please see [[postgres]] for details on various access methods, which include:<br />
# Built-in SQLdb support. Use component '''TPQConnection''' from palette '''SQLdb'''<br />
# Zeos. Use component '''TZConnection''' with protocol 'postgresql' from palette '''Zeos Access'''<br />
<br />
== Lazarus and SQLite ==<br />
SQLite is an embedded database; the database code can be distributed as a library (.dll/.so/.dylib) with your application to make it self-contained (comparable to Firebird embedded). SQLite is quite popular due to its relative simplicity, speed, small size and cross-platform support.<br />
<br />
Please see the [[SQLite]] page for details on various access methods, which include:<br />
# Built-in SQLDb support<br />
# Zeos<br />
# SQLitePass <br />
# TSQLite3Dataset<br />
<br />
== Lazarus and dBase ==<br />
<br />
[[user:Tonymaro|Tony Maro]]<br />
<br />
You might also want to visit the [[Lazarus Tdbf Tutorial|TDbf Tutorial page]]<br />
<br />
FPC includes a simple database component that is similar in function to the Delphi TTable component called "TDbf" ([http://tdbf.sourceforge.net/ TDbf Website]) that supports a subset of features for dBase files. It is not installed by default, so you will first need to install the Lazarus package from the "lazarus/components/tdbf" directory and rebuild your Lazarus IDE. It will then appear next to the TDatasource in your component palette (Data Access tab).<br />
<br />
The TDbf component has an advantage over other database components in that it doesn't require any sort of runtime database engine. However it's not the best option for large database applications.<br />
<br />
It's very easy to use. Simply drop a TDbf on your form, set the runtime path to the directory that your database files will be in, set the table name, and link it to your TDatasource component.<br />
<br />
Real functionality requires a bit more effort, however. If a table doesn't already exist, you'll need to create it programmatically, unless there's a compatible table designer I'm not familiar with.<br />
Note: Current version of OpenOffice/LibreOffice (3.x) contains OpenOffice Base, which can create dbf files in a somewhat user-friendly way.<br />
<br />
Attempting to open a nonexistent table will generate an error. Tables can be created programmatically through the component after the runtime path and table name are set.<br />
<br />
For instance, to create a table called "dvds" to store your DVD collection you would drop it on your form, set the runtime path, and set the table name to "dvds". The resulting file will be called "dvds.dbf".<br />
<br />
In your code, insert the following:<br />
<br />
<syntaxhighlight>Dbf1.FilePathFull := '/path/to/my/database';<br />
Dbf1.TableName := 'dvds';<br />
With Dbf1.FieldDefs do begin<br />
Add('Name', ftString, 80, True);<br />
Add('Description', ftMemo, 0, False);<br />
Add('Rating', ftString, 5, False);<br />
end;<br />
Dbf1.CreateTable;</syntaxhighlight><br />
<br />
When this code is run, your DVD collection table will be created. After that, all data aware components linked through the TDatasource to this component will allow easy access to the data. <br />
<br />
Adding an index is a little different from your typical TTable. It must be done after the database is open. You use the same method also to rebuild the indices. For instance:<br />
<br />
<syntaxhighlight>Dbf1.Exclusive := True;<br />
Dbf1.Open;<br />
Dbf1.AddIndex('dvdsname','Name',[ixPrimary, ixUnique, ixCaseInsensitive]);<br />
Dbf1.AddIndex('rating.ndx', 'Rating', [ixCaseInsensitive]);<br />
Dbf1.Close;</syntaxhighlight><br />
<br />
The first (primary) index will be a file called "dvdsname.mdx" and the second will be a file named "rating.ndx" so in a multiple table database you must be careful not to use the same file name again.<br />
<br />
Please see [[Lazarus Tdbf Tutorial|TDbf Tutorial page]] for more details, but hopefully this will get those old Delphi programmers up and running with databases in Lazarus!<br />
<br />
===Searching and Displaying a data set===<br />
<br />
[[user:svbfieldview.net|Simon Batty]]<br />
<br />
In this example I wanted to search a database of books for all the titles an author has listed<br />
and then display the list in a memo box<br />
<syntaxhighlight>Dbf1.FilePathFull := '/home/somelocatio/database_location/'; // path to the database directory<br />
Dbf1.TableName := 'books.dbase'; // database file (including extension)<br />
DbF1.Open;<br />
memo1.Clear; // clear the memo box<br />
<br />
Dbf1.FilterOptions := [foCaseInsensitive];<br />
Df1.Filter := 'AU=' + QuotedStr('anauthor'); // AU is the field name containing the authors<br />
<br />
Dbf1.Filtered := true; // This selects the filtered set<br />
Dbf1.First; // moves the the first filtered data<br />
while not dbf1.EOF do // prints the titles that match the author to the memo box<br />
begin<br />
memo1.Append(Dbf1.FieldByName('TI').AsString); // TI is the field name for titles<br />
dbf1.next; // use .next here NOT .findnext!<br />
end;<br />
Dbf1.Close;</syntaxhighlight> <br />
<br />
Note that you can use Ddf1.findfirst to get the first record in the filtered set, then use <br />
Dbf1.next to move though the data. I found that using Dbf1.Findnext just causes the program to hang. <br />
<br />
This database was generated using TurboBD that came with the Kylix 1. I cannot get TurboBD tables to work with Lazarus, however you can download a command line tool from TurboDB's website that allows you to convert TurboDB table to other formats.<br />
<br />
== Using TSdfDataset and TFixedDataset ==<br />
<br />
TSdfDataset and TFixedDataset are two simple datasets which offer a very simple textual storage format. These datasets are very convenient for small databases, because they are fully implemented as an object pascal unit, and thus require no external libraries, and because their textual format allows them to be easely edited with a text editor.<br />
<br />
To start with this formats, a initial database file should be created. The format is very simple, so use a text editor to do this.<br />
<br />
Bellow is a sample database for TSdfDataset. Note that the first line has the names of the fields and that we are using commas as separators:<br />
<br />
<pre>ID,NAMEEN,NAMEPT,HEIGHT,WIDTH,PINS,DRAWINGCODE<br />
1,resistor,resistor,1,1,1,LINE<br />
2,capacitor,capacitor,1,1,1,LINE<br />
3,transistor npn,transistor npn</pre><br />
<br />
And here is an example database for using with TFixedDataset. Each record occupies a fixed amount of space, and if the field is smaller then it, spaces should be used to fill the remaining size.<br />
<br />
<pre>Name = 15 chars; Surname = 15 chars; Tell = 10 chars; e_mail = 20 chars;<br />
Piet Pompies piet@pompies.net</pre><br />
<br />
=== Using the datasets directly ===<br />
<br />
Sometimes it is useful to create the dataset and work with it completely in code, and the following code will do exactly this. Note some peculiarities of TSdfDataset/TFixedDataset:<br />
<br />
* The lines in the database can have a maximum size of about 300. A fix is being researched.<br />
* It is necessary to add the field definitions. Some datasets are able to fill this information alone from the database file<br />
* One should set FirstLineAsSchema to true, to indicate that the first line includes the field names and positions<br />
* The Delimiter property holds the separator for the fields. It will not be possible to use this char in strings in the database. Similarly it will not be possible to have lineendings in the database because they mark the change between records. It's possible to overcome this by substituting the needed comma or line ending with another not often used char, like # for example. So that when showing the data on screen all # chars could be converted to line endings and the inverse when storing data back to the database. The ReplaceString routine is useful here.<br />
<br />
<syntaxhighlight><br />
uses sdfdata, db;<br />
<br />
constructor TComponentsDatabase.Create;<br />
var<br />
FDataset: TSdfDataset;<br />
begin<br />
inherited Create;<br />
<br />
FDataset := TSdfDataset.Create(nil);<br />
FDataset.FileName := vConfigurations.ComponentsDBFile;<br />
<br />
// Not necessary with TSdfDataset<br />
// FDataset.TableName := STR_DB_COMPONENTS_TABLE;<br />
// FDataset.PrimaryKey := STR_DB_COMPONENTS_ID;<br />
<br />
// Adds field definitions<br />
FDataset.FieldDefs.Add('ID', ftString);<br />
FDataset.FieldDefs.Add('NAMEEN', ftString);<br />
FDataset.FieldDefs.Add('NAMEPT', ftString);<br />
FDataset.FieldDefs.Add('HEIGHT', ftString);<br />
FDataset.FieldDefs.Add('WIDTH', ftString);<br />
FDataset.FieldDefs.Add('PINS', ftString);<br />
FDataset.FieldDefs.Add('DRAWINGCODE', ftString);<br />
<br />
// Necessary for TSdfDataset<br />
FDataset.Delimiter := ',';<br />
FDataset.FirstLineAsSchema := True;<br />
<br />
FDataset.Active := True;<br />
<br />
// Sets the initial record<br />
CurrentRecNo := 1;<br />
FDataset.First;<br />
end;</syntaxhighlight><br />
<br />
When using TSdfDataset directly be aware that RecNo, although it is implemented, does not work as a way to move through the dataset whether reading or writing records. The standard navigation routines like First, Next, Prior and Last work as expected, so you need to use them rather than RecNo.<br />
If you are used to using absolute record numbers to navigate around a database you can implement your own version of RecNo. Declare a global longint variable called CurrentRecNo which will hold the current RecNo value. Remember that this variable will have the same convention as RecNo, so the first record has number 1 (it is not zero-based). After activating the database initialize the database to the first record with TSdfDataset.First and set CurrentRecNo := 1<br />
<br />
<syntaxhighlight>{@@<br />
Moves to the desired record using TDataset.Next and TDataset.Prior<br />
This avoids using TDataset.RecNo which doesn't navigate reliably in any dataset.<br />
<br />
@param AID Indicates the record number. The first record has number 1<br />
}<br />
procedure TComponentsDatabase.GoToRec(AID: Integer);<br />
begin<br />
// We are before the desired record, move forward<br />
if CurrentRecNo < AID then<br />
begin<br />
while (not FDataset.EOF) and (CurrentRecNo < AID) do<br />
begin<br />
FDataset.Next;<br />
FDataset.CursorPosChanged;<br />
Inc(CurrentRecNo);<br />
end;<br />
end<br />
// We are after the desired record, move back<br />
else if CurrentRecNo > AID then<br />
begin<br />
while (CurrentRecNo >= 1) and (CurrentRecNo > AID) do<br />
begin<br />
FDataset.Prior;<br />
FDataset.CursorPosChanged;<br />
Dec(CurrentRecNo);<br />
end;<br />
end;<br />
end;</syntaxhighlight><br />
<br />
=== Using with data-aware controls ===<br />
<br />
== Lazarus and Advantage Database Server ==<br />
* Please see [[Advantage Database Server]] for details on using Advantage Database Server<br />
<br />
==See also==<br />
* [[Database_field_type]]<br />
* [[Databases]]<br />
* [[Databases in Lazarus]]<br />
* [[Firebird in action]]<br />
* [[How to write in-memory database applications in Lazarus/FPC]]<br />
* [[Lazarus DB Faq]]<br />
* [[Lazarus Tdbf Tutorial]]<br />
* [[MS Access]]<br />
* [[multi-tier_options_with_fpc|Multi-tier options with FPC]]<br />
* [[MySQLDatabases]]<br />
* [[ODBCConn]]<br />
* [[SQLdb Tutorial1]]<br />
* [[SqlDBHowto]]<br />
* [[SQLite]]<br />
* [[tiOPF]] - a free and open source Object Persistence Framework.<br />
* [[Zeos tutorial]]<br />
<br />
==External links==<br />
<br />
* [http://pdo.sourceforge.net Pascal Data Objects] - a database API that worked for both FPC and Delphi and utilises native MySQL libraries for version 4.1 and 5.0 and Firebird SQL 1.5, and 2.0. It's inspired by PHP's PDO class.<br />
* [http://lazaruszeos.blogspot.com Zeos+SQLite Tutorial] - Good tutorial using screenshots and screencasts it explain how to use SQLite and Zeos, spanish (google translate does a good work in translating it to english)<br />
<br />
<br />
[[Category:Databases]]<br />
[[Category:Tutorials]]</div>Mario13https://wiki.freepascal.org/index.php?title=Lazarus_Database_Overview&diff=62545Lazarus Database Overview2012-10-08T15:10:04Z<p>Mario13: /* Lazarus and PostgreSQL */</p>
<hr />
<div>{{Translate}}<br />
<br />
== Overview ==<br />
<br />
This article is an overview of the which databases can work with Lazarus.<br />
<br />
Lazarus supports several databases out of the box (using e.g. the SQLDB framework), however the developer must install the required packages (client libraries) for each one. <br />
<br />
You can access the database through code or by dropping components on a form. The data-aware components represent fields and are connected by setting the DataSource property to point to a TDataSource. The Datasource represents a table and is connected to the database components (examples: ''TPSQLDatabase'', ''TSQLiteDataSet'') by setting the DataSet property. The data-aware components are located on the "Data Controls" tab. The Datasource and the database controls are located on the "Data Access" tab.<br />
<br />
== Lazarus and Interbase / Firebird ==<br />
* Please see [[Firebird_in_action|Firebird in action]] for details on various access methods, which include<br />
# Built-in SQLDB support<br />
# FBLib<br />
# IBX<br />
# PDO<br />
# Zeos<br />
<br />
For a tutorial that leads you through creating a Lazarus GUI for a Firebird database, see:<br />
* [[SQLdb Tutorial1]]<br />
<br />
<br />
== Lazarus and MySQL ==<br />
* Please see [[mysql]] for details on various access methods, which include:<br />
# Built-in SQLDB support<br />
# PDO<br />
# Zeos<br />
<br />
== Lazarus and MSSQL/Sybase ==<br />
You can connect to Microsoft SQL Server databases using<br />
# The built-in SQLdb (recent Lazarus/FPC 2.6.1+): TMSSQLConnection (MS SQL) and TSybaseConnection (Sybase ASE)<br />
## On Windows by default it use FreeTDS library '''dblib.dll'''. By modifying FPC file '''dblib.pas''' it could use native library ntwdblib.dll (in this case FPC needs to be recompiled).<br />
## On Linux by default it use '''libsybdb.so''' which is FreeTDS library (for example, in Debian is in package '''libsybd5''').<br />
# Zeos (latest CVS, see links to Zeos elsewhere on this page)<br />
## On Windows you can choose between native library ntwdblib.dll (protocol '''mssql''') or FreeTDS libraries (protocol '''FreeTDS_MsSQL-nnnn''') where nnnn is one of four variants depending on the server version. <br />
## On Linux the only way is with FreeTDS protocols and libraries (use '''libsybdb.so''').<br />
# ODBC (MS SQL and Sybase ASE) with SQLdb TODBCConnection<br />
## On Windows it uses native ODBC Microsoft libraries (like sqlsrv32.dll for SQL server 2000)<br />
## On Linux it uses unixODBC + FreeTDS (packages unixodbc or iodbc, and tdsodbc)<br />
Please see the FPC and Lazarus help files for details on using SQLDB with Sybase ASE and MS SQL Server.<br />
<br />
Note1: In any of the above forms, if you use native Microsoft Libraries (over Windows) it could be possible to connect to remote server with Named Pipes or with TCP/IP with fixed port (like 1433). If you use native libraries over Wine in Linux only TCP/IP is working, Named Pipes will not work (for now). On the other hand, if you use FreeTDS libraries, connecting with Named Pipes is not supported, only TCP/IP connections with fixed port (like 1433) are supported.<br />
<br />
Note2: Lazarus 1.0 was released with FPC 2.6.0 and does not include TMSSQLConnection or TSybaseConnection. If you want these, it might be easiest to download a snapshot of the latest Lazarus built with FPC 2.6.1, optinally installing that in a directory different from your Lazarus 1.0 version. You can use --primary-config-path to set up a separate environment for the Lazarus snapshot (see [[Multiple_Lazarus]])<br />
<br />
== Lazarus and ODBC ==<br />
ODBC is a general database connection standard which is available on Linux, Windows and OSX. You will need an ODBC driver from your database vendor and set up an ODBC "data source" (also known as DSN).<br />
You can use the SQLDB components (TODBCConnection) to connect to an ODBC data soruce.<br />
See [[ODBCConn]] for more details and examples<br />
<br />
== Lazarus and Oracle ==<br />
* Acces methods include:<br />
# Built-in SQLDB support<br />
# Zeos<br />
<br />
== Lazarus and PostgreSQL ==<br />
* Please see [[postgres]] for details on various access methods, which include:<br />
# Built-in SQLdb support. Use component '''TPQConnection''' from palette '''SQLdb'''<br />
# Zeos. Use component '''TZConnection''' with protocol 'postgresql' from palette '''Zeos Access'''<br />
<br />
== Lazarus and SQLite ==<br />
SQLite is an embedded database; the database code can be distributed as a library (.dll/.so/.dylib) with your application to make it self-contained (comparable to Firebird embedded). SQLite is quite popular due to its relative simplicity, speed, small size and cross-platform support.<br />
<br />
Please see the [[SQLite]] page for details on various access methods, which include:<br />
# Built-in SQLDb support<br />
# Zeos<br />
# SQLitePass <br />
# TSQLite3Dataset<br />
<br />
== Lazarus and dBase ==<br />
<br />
[[user:Tonymaro|Tony Maro]]<br />
<br />
You might also want to visit the [[Lazarus Tdbf Tutorial|TDbf Tutorial page]]<br />
<br />
FPC includes a simple database component that is similar in function to the Delphi TTable component called "TDbf" ([http://tdbf.sourceforge.net/ TDbf Website]) that supports a subset of features for dBase files. It is not installed by default, so you will first need to install the Lazarus package from the "lazarus/components/tdbf" directory and rebuild your Lazarus IDE. It will then appear next to the TDatasource in your component palette (Data Access tab).<br />
<br />
The TDbf component has an advantage over other database components in that it doesn't require any sort of runtime database engine. However it's not the best option for large database applications.<br />
<br />
It's very easy to use. Simply drop a TDbf on your form, set the runtime path to the directory that your database files will be in, set the table name, and link it to your TDatasource component.<br />
<br />
Real functionality requires a bit more effort, however. If a table doesn't already exist, you'll need to create it programmatically, unless there's a compatible table designer I'm not familiar with.<br />
Note: Current version of OpenOffice/LibreOffice (3.x) contains OpenOffice Base, which can create dbf files in a somewhat user-friendly way.<br />
<br />
Attempting to open a nonexistent table will generate an error. Tables can be created programmatically through the component after the runtime path and table name are set.<br />
<br />
For instance, to create a table called "dvds" to store your DVD collection you would drop it on your form, set the runtime path, and set the table name to "dvds". The resulting file will be called "dvds.dbf".<br />
<br />
In your code, insert the following:<br />
<br />
<syntaxhighlight>Dbf1.FilePathFull := '/path/to/my/database';<br />
Dbf1.TableName := 'dvds';<br />
With Dbf1.FieldDefs do begin<br />
Add('Name', ftString, 80, True);<br />
Add('Description', ftMemo, 0, False);<br />
Add('Rating', ftString, 5, False);<br />
end;<br />
Dbf1.CreateTable;</syntaxhighlight><br />
<br />
When this code is run, your DVD collection table will be created. After that, all data aware components linked through the TDatasource to this component will allow easy access to the data. <br />
<br />
Adding an index is a little different from your typical TTable. It must be done after the database is open. You use the same method also to rebuild the indices. For instance:<br />
<br />
<syntaxhighlight>Dbf1.Exclusive := True;<br />
Dbf1.Open;<br />
Dbf1.AddIndex('dvdsname','Name',[ixPrimary, ixUnique, ixCaseInsensitive]);<br />
Dbf1.AddIndex('rating.ndx', 'Rating', [ixCaseInsensitive]);<br />
Dbf1.Close;</syntaxhighlight><br />
<br />
The first (primary) index will be a file called "dvdsname.mdx" and the second will be a file named "rating.ndx" so in a multiple table database you must be careful not to use the same file name again.<br />
<br />
Please see [[Lazarus Tdbf Tutorial|TDbf Tutorial page]] for more details, but hopefully this will get those old Delphi programmers up and running with databases in Lazarus!<br />
<br />
===Searching and Displaying a data set===<br />
<br />
[[user:svbfieldview.net|Simon Batty]]<br />
<br />
In this example I wanted to search a database of books for all the titles an author has listed<br />
and then display the list in a memo box<br />
<syntaxhighlight>Dbf1.FilePathFull := '/home/somelocatio/database_location/'; // path to the database directory<br />
Dbf1.TableName := 'books.dbase'; // database file (including extension)<br />
DbF1.Open;<br />
memo1.Clear; // clear the memo box<br />
<br />
Dbf1.FilterOptions := [foCaseInsensitive];<br />
Df1.Filter := 'AU=' + QuotedStr('anauthor'); // AU is the field name containing the authors<br />
<br />
Dbf1.Filtered := true; // This selects the filtered set<br />
Dbf1.First; // moves the the first filtered data<br />
while not dbf1.EOF do // prints the titles that match the author to the memo box<br />
begin<br />
memo1.Append(Dbf1.FieldByName('TI').AsString); // TI is the field name for titles<br />
dbf1.next; // use .next here NOT .findnext!<br />
end;<br />
Dbf1.Close;</syntaxhighlight> <br />
<br />
Note that you can use Ddf1.findfirst to get the first record in the filtered set, then use <br />
Dbf1.next to move though the data. I found that using Dbf1.Findnext just causes the program to hang. <br />
<br />
This database was generated using TurboBD that came with the Kylix 1. I cannot get TurboBD tables to work with Lazarus, however you can download a command line tool from TurboDB's website that allows you to convert TurboDB table to other formats.<br />
<br />
== Using TSdfDataset and TFixedDataset ==<br />
<br />
TSdfDataset and TFixedDataset are two simple datasets which offer a very simple textual storage format. These datasets are very convenient for small databases, because they are fully implemented as an object pascal unit, and thus require no external libraries, and because their textual format allows them to be easely edited with a text editor.<br />
<br />
To start with this formats, a initial database file should be created. The format is very simple, so use a text editor to do this.<br />
<br />
Bellow is a sample database for TSdfDataset. Note that the first line has the names of the fields and that we are using commas as separators:<br />
<br />
<pre>ID,NAMEEN,NAMEPT,HEIGHT,WIDTH,PINS,DRAWINGCODE<br />
1,resistor,resistor,1,1,1,LINE<br />
2,capacitor,capacitor,1,1,1,LINE<br />
3,transistor npn,transistor npn</pre><br />
<br />
And here is an example database for using with TFixedDataset. Each record occupies a fixed amount of space, and if the field is smaller then it, spaces should be used to fill the remaining size.<br />
<br />
<pre>Name = 15 chars; Surname = 15 chars; Tell = 10 chars; e_mail = 20 chars;<br />
Piet Pompies piet@pompies.net</pre><br />
<br />
=== Using the datasets directly ===<br />
<br />
Sometimes it is useful to create the dataset and work with it completely in code, and the following code will do exactly this. Note some peculiarities of TSdfDataset/TFixedDataset:<br />
<br />
* The lines in the database can have a maximum size of about 300. A fix is being researched.<br />
* It is necessary to add the field definitions. Some datasets are able to fill this information alone from the database file<br />
* One should set FirstLineAsSchema to true, to indicate that the first line includes the field names and positions<br />
* The Delimiter property holds the separator for the fields. It will not be possible to use this char in strings in the database. Similarly it will not be possible to have lineendings in the database because they mark the change between records. It's possible to overcome this by substituting the needed comma or line ending with another not often used char, like # for example. So that when showing the data on screen all # chars could be converted to line endings and the inverse when storing data back to the database. The ReplaceString routine is useful here.<br />
<br />
<syntaxhighlight><br />
uses sdfdata, db;<br />
<br />
constructor TComponentsDatabase.Create;<br />
var<br />
FDataset: TSdfDataset;<br />
begin<br />
inherited Create;<br />
<br />
FDataset := TSdfDataset.Create(nil);<br />
FDataset.FileName := vConfigurations.ComponentsDBFile;<br />
<br />
// Not necessary with TSdfDataset<br />
// FDataset.TableName := STR_DB_COMPONENTS_TABLE;<br />
// FDataset.PrimaryKey := STR_DB_COMPONENTS_ID;<br />
<br />
// Adds field definitions<br />
FDataset.FieldDefs.Add('ID', ftString);<br />
FDataset.FieldDefs.Add('NAMEEN', ftString);<br />
FDataset.FieldDefs.Add('NAMEPT', ftString);<br />
FDataset.FieldDefs.Add('HEIGHT', ftString);<br />
FDataset.FieldDefs.Add('WIDTH', ftString);<br />
FDataset.FieldDefs.Add('PINS', ftString);<br />
FDataset.FieldDefs.Add('DRAWINGCODE', ftString);<br />
<br />
// Necessary for TSdfDataset<br />
FDataset.Delimiter := ',';<br />
FDataset.FirstLineAsSchema := True;<br />
<br />
FDataset.Active := True;<br />
<br />
// Sets the initial record<br />
CurrentRecNo := 1;<br />
FDataset.First;<br />
end;</syntaxhighlight><br />
<br />
When using TSdfDataset directly be aware that RecNo, although it is implemented, does not work as a way to move through the dataset whether reading or writing records. The standard navigation routines like First, Next, Prior and Last work as expected, so you need to use them rather than RecNo.<br />
If you are used to using absolute record numbers to navigate around a database you can implement your own version of RecNo. Declare a global longint variable called CurrentRecNo which will hold the current RecNo value. Remember that this variable will have the same convention as RecNo, so the first record has number 1 (it is not zero-based). After activating the database initialize the database to the first record with TSdfDataset.First and set CurrentRecNo := 1<br />
<br />
<syntaxhighlight>{@@<br />
Moves to the desired record using TDataset.Next and TDataset.Prior<br />
This avoids using TDataset.RecNo which doesn't navigate reliably in any dataset.<br />
<br />
@param AID Indicates the record number. The first record has number 1<br />
}<br />
procedure TComponentsDatabase.GoToRec(AID: Integer);<br />
begin<br />
// We are before the desired record, move forward<br />
if CurrentRecNo < AID then<br />
begin<br />
while (not FDataset.EOF) and (CurrentRecNo < AID) do<br />
begin<br />
FDataset.Next;<br />
FDataset.CursorPosChanged;<br />
Inc(CurrentRecNo);<br />
end;<br />
end<br />
// We are after the desired record, move back<br />
else if CurrentRecNo > AID then<br />
begin<br />
while (CurrentRecNo >= 1) and (CurrentRecNo > AID) do<br />
begin<br />
FDataset.Prior;<br />
FDataset.CursorPosChanged;<br />
Dec(CurrentRecNo);<br />
end;<br />
end;<br />
end;</syntaxhighlight><br />
<br />
=== Using with data-aware controls ===<br />
<br />
== Lazarus and Advantage Database Server ==<br />
* Please see [[Advantage Database Server]] for details on using Advantage Database Server<br />
<br />
==See also==<br />
* [[Database_field_type]]<br />
* [[Databases]]<br />
* [[Databases in Lazarus]]<br />
* [[Firebird in action]]<br />
* [[How to write in-memory database applications in Lazarus/FPC]]<br />
* [[Lazarus DB Faq]]<br />
* [[Lazarus Tdbf Tutorial]]<br />
* [[MS Access]]<br />
* [[multi-tier_options_with_fpc|Multi-tier options with FPC]]<br />
* [[MySQLDatabases]]<br />
* [[ODBCConn]]<br />
* [[SQLdb Tutorial1]]<br />
* [[SqlDBHowto]]<br />
* [[SQLite]]<br />
* [[tiOPF]] - a free and open source Object Persistence Framework.<br />
* [[Zeos tutorial]]<br />
<br />
==External links==<br />
<br />
* [http://pdo.sourceforge.net Pascal Data Objects] - a database API that worked for both FPC and Delphi and utilises native MySQL libraries for version 4.1 and 5.0 and Firebird SQL 1.5, and 2.0. It's inspired by PHP's PDO class.<br />
* [http://lazaruszeos.blogspot.com Zeos+SQLite Tutorial] - Good tutorial using screenshots and screencasts it explain how to use SQLite and Zeos, spanish (google translate does a good work in translating it to english)<br />
<br />
<br />
[[Category:Databases]]<br />
[[Category:Tutorials]]</div>Mario13https://wiki.freepascal.org/index.php?title=Lazarus_Database_Overview&diff=62544Lazarus Database Overview2012-10-08T15:04:07Z<p>Mario13: /* Lazarus and MSSQL/Sybase */</p>
<hr />
<div>{{Translate}}<br />
<br />
== Overview ==<br />
<br />
This article is an overview of the which databases can work with Lazarus.<br />
<br />
Lazarus supports several databases out of the box (using e.g. the SQLDB framework), however the developer must install the required packages (client libraries) for each one. <br />
<br />
You can access the database through code or by dropping components on a form. The data-aware components represent fields and are connected by setting the DataSource property to point to a TDataSource. The Datasource represents a table and is connected to the database components (examples: ''TPSQLDatabase'', ''TSQLiteDataSet'') by setting the DataSet property. The data-aware components are located on the "Data Controls" tab. The Datasource and the database controls are located on the "Data Access" tab.<br />
<br />
== Lazarus and Interbase / Firebird ==<br />
* Please see [[Firebird_in_action|Firebird in action]] for details on various access methods, which include<br />
# Built-in SQLDB support<br />
# FBLib<br />
# IBX<br />
# PDO<br />
# Zeos<br />
<br />
For a tutorial that leads you through creating a Lazarus GUI for a Firebird database, see:<br />
* [[SQLdb Tutorial1]]<br />
<br />
<br />
== Lazarus and MySQL ==<br />
* Please see [[mysql]] for details on various access methods, which include:<br />
# Built-in SQLDB support<br />
# PDO<br />
# Zeos<br />
<br />
== Lazarus and MSSQL/Sybase ==<br />
You can connect to Microsoft SQL Server databases using<br />
# The built-in SQLdb (recent Lazarus/FPC 2.6.1+): TMSSQLConnection (MS SQL) and TSybaseConnection (Sybase ASE)<br />
## On Windows by default it use FreeTDS library '''dblib.dll'''. By modifying FPC file '''dblib.pas''' it could use native library ntwdblib.dll (in this case FPC needs to be recompiled).<br />
## On Linux by default it use '''libsybdb.so''' which is FreeTDS library (for example, in Debian is in package '''libsybd5''').<br />
# Zeos (latest CVS, see links to Zeos elsewhere on this page)<br />
## On Windows you can choose between native library ntwdblib.dll (protocol '''mssql''') or FreeTDS libraries (protocol '''FreeTDS_MsSQL-nnnn''') where nnnn is one of four variants depending on the server version. <br />
## On Linux the only way is with FreeTDS protocols and libraries (use '''libsybdb.so''').<br />
# ODBC (MS SQL and Sybase ASE) with SQLdb TODBCConnection<br />
## On Windows it uses native ODBC Microsoft libraries (like sqlsrv32.dll for SQL server 2000)<br />
## On Linux it uses unixODBC + FreeTDS (packages unixodbc or iodbc, and tdsodbc)<br />
Please see the FPC and Lazarus help files for details on using SQLDB with Sybase ASE and MS SQL Server.<br />
<br />
Note1: In any of the above forms, if you use native Microsoft Libraries (over Windows) it could be possible to connect to remote server with Named Pipes or with TCP/IP with fixed port (like 1433). If you use native libraries over Wine in Linux only TCP/IP is working, Named Pipes will not work (for now). On the other hand, if you use FreeTDS libraries, connecting with Named Pipes is not supported, only TCP/IP connections with fixed port (like 1433) are supported.<br />
<br />
Note2: Lazarus 1.0 was released with FPC 2.6.0 and does not include TMSSQLConnection or TSybaseConnection. If you want these, it might be easiest to download a snapshot of the latest Lazarus built with FPC 2.6.1, optinally installing that in a directory different from your Lazarus 1.0 version. You can use --primary-config-path to set up a separate environment for the Lazarus snapshot (see [[Multiple_Lazarus]])<br />
<br />
== Lazarus and ODBC ==<br />
ODBC is a general database connection standard which is available on Linux, Windows and OSX. You will need an ODBC driver from your database vendor and set up an ODBC "data source" (also known as DSN).<br />
You can use the SQLDB components (TODBCConnection) to connect to an ODBC data soruce.<br />
See [[ODBCConn]] for more details and examples<br />
<br />
== Lazarus and Oracle ==<br />
* Acces methods include:<br />
# Built-in SQLDB support<br />
# Zeos<br />
<br />
== Lazarus and PostgreSQL ==<br />
* Please see [[postgres]] for details on various access methods, which include:<br />
# Built-in SQLDB support<br />
# Zeos<br />
<br />
== Lazarus and SQLite ==<br />
SQLite is an embedded database; the database code can be distributed as a library (.dll/.so/.dylib) with your application to make it self-contained (comparable to Firebird embedded). SQLite is quite popular due to its relative simplicity, speed, small size and cross-platform support.<br />
<br />
Please see the [[SQLite]] page for details on various access methods, which include:<br />
# Built-in SQLDb support<br />
# Zeos<br />
# SQLitePass <br />
# TSQLite3Dataset<br />
<br />
== Lazarus and dBase ==<br />
<br />
[[user:Tonymaro|Tony Maro]]<br />
<br />
You might also want to visit the [[Lazarus Tdbf Tutorial|TDbf Tutorial page]]<br />
<br />
FPC includes a simple database component that is similar in function to the Delphi TTable component called "TDbf" ([http://tdbf.sourceforge.net/ TDbf Website]) that supports a subset of features for dBase files. It is not installed by default, so you will first need to install the Lazarus package from the "lazarus/components/tdbf" directory and rebuild your Lazarus IDE. It will then appear next to the TDatasource in your component palette (Data Access tab).<br />
<br />
The TDbf component has an advantage over other database components in that it doesn't require any sort of runtime database engine. However it's not the best option for large database applications.<br />
<br />
It's very easy to use. Simply drop a TDbf on your form, set the runtime path to the directory that your database files will be in, set the table name, and link it to your TDatasource component.<br />
<br />
Real functionality requires a bit more effort, however. If a table doesn't already exist, you'll need to create it programmatically, unless there's a compatible table designer I'm not familiar with.<br />
Note: Current version of OpenOffice/LibreOffice (3.x) contains OpenOffice Base, which can create dbf files in a somewhat user-friendly way.<br />
<br />
Attempting to open a nonexistent table will generate an error. Tables can be created programmatically through the component after the runtime path and table name are set.<br />
<br />
For instance, to create a table called "dvds" to store your DVD collection you would drop it on your form, set the runtime path, and set the table name to "dvds". The resulting file will be called "dvds.dbf".<br />
<br />
In your code, insert the following:<br />
<br />
<syntaxhighlight>Dbf1.FilePathFull := '/path/to/my/database';<br />
Dbf1.TableName := 'dvds';<br />
With Dbf1.FieldDefs do begin<br />
Add('Name', ftString, 80, True);<br />
Add('Description', ftMemo, 0, False);<br />
Add('Rating', ftString, 5, False);<br />
end;<br />
Dbf1.CreateTable;</syntaxhighlight><br />
<br />
When this code is run, your DVD collection table will be created. After that, all data aware components linked through the TDatasource to this component will allow easy access to the data. <br />
<br />
Adding an index is a little different from your typical TTable. It must be done after the database is open. You use the same method also to rebuild the indices. For instance:<br />
<br />
<syntaxhighlight>Dbf1.Exclusive := True;<br />
Dbf1.Open;<br />
Dbf1.AddIndex('dvdsname','Name',[ixPrimary, ixUnique, ixCaseInsensitive]);<br />
Dbf1.AddIndex('rating.ndx', 'Rating', [ixCaseInsensitive]);<br />
Dbf1.Close;</syntaxhighlight><br />
<br />
The first (primary) index will be a file called "dvdsname.mdx" and the second will be a file named "rating.ndx" so in a multiple table database you must be careful not to use the same file name again.<br />
<br />
Please see [[Lazarus Tdbf Tutorial|TDbf Tutorial page]] for more details, but hopefully this will get those old Delphi programmers up and running with databases in Lazarus!<br />
<br />
===Searching and Displaying a data set===<br />
<br />
[[user:svbfieldview.net|Simon Batty]]<br />
<br />
In this example I wanted to search a database of books for all the titles an author has listed<br />
and then display the list in a memo box<br />
<syntaxhighlight>Dbf1.FilePathFull := '/home/somelocatio/database_location/'; // path to the database directory<br />
Dbf1.TableName := 'books.dbase'; // database file (including extension)<br />
DbF1.Open;<br />
memo1.Clear; // clear the memo box<br />
<br />
Dbf1.FilterOptions := [foCaseInsensitive];<br />
Df1.Filter := 'AU=' + QuotedStr('anauthor'); // AU is the field name containing the authors<br />
<br />
Dbf1.Filtered := true; // This selects the filtered set<br />
Dbf1.First; // moves the the first filtered data<br />
while not dbf1.EOF do // prints the titles that match the author to the memo box<br />
begin<br />
memo1.Append(Dbf1.FieldByName('TI').AsString); // TI is the field name for titles<br />
dbf1.next; // use .next here NOT .findnext!<br />
end;<br />
Dbf1.Close;</syntaxhighlight> <br />
<br />
Note that you can use Ddf1.findfirst to get the first record in the filtered set, then use <br />
Dbf1.next to move though the data. I found that using Dbf1.Findnext just causes the program to hang. <br />
<br />
This database was generated using TurboBD that came with the Kylix 1. I cannot get TurboBD tables to work with Lazarus, however you can download a command line tool from TurboDB's website that allows you to convert TurboDB table to other formats.<br />
<br />
== Using TSdfDataset and TFixedDataset ==<br />
<br />
TSdfDataset and TFixedDataset are two simple datasets which offer a very simple textual storage format. These datasets are very convenient for small databases, because they are fully implemented as an object pascal unit, and thus require no external libraries, and because their textual format allows them to be easely edited with a text editor.<br />
<br />
To start with this formats, a initial database file should be created. The format is very simple, so use a text editor to do this.<br />
<br />
Bellow is a sample database for TSdfDataset. Note that the first line has the names of the fields and that we are using commas as separators:<br />
<br />
<pre>ID,NAMEEN,NAMEPT,HEIGHT,WIDTH,PINS,DRAWINGCODE<br />
1,resistor,resistor,1,1,1,LINE<br />
2,capacitor,capacitor,1,1,1,LINE<br />
3,transistor npn,transistor npn</pre><br />
<br />
And here is an example database for using with TFixedDataset. Each record occupies a fixed amount of space, and if the field is smaller then it, spaces should be used to fill the remaining size.<br />
<br />
<pre>Name = 15 chars; Surname = 15 chars; Tell = 10 chars; e_mail = 20 chars;<br />
Piet Pompies piet@pompies.net</pre><br />
<br />
=== Using the datasets directly ===<br />
<br />
Sometimes it is useful to create the dataset and work with it completely in code, and the following code will do exactly this. Note some peculiarities of TSdfDataset/TFixedDataset:<br />
<br />
* The lines in the database can have a maximum size of about 300. A fix is being researched.<br />
* It is necessary to add the field definitions. Some datasets are able to fill this information alone from the database file<br />
* One should set FirstLineAsSchema to true, to indicate that the first line includes the field names and positions<br />
* The Delimiter property holds the separator for the fields. It will not be possible to use this char in strings in the database. Similarly it will not be possible to have lineendings in the database because they mark the change between records. It's possible to overcome this by substituting the needed comma or line ending with another not often used char, like # for example. So that when showing the data on screen all # chars could be converted to line endings and the inverse when storing data back to the database. The ReplaceString routine is useful here.<br />
<br />
<syntaxhighlight><br />
uses sdfdata, db;<br />
<br />
constructor TComponentsDatabase.Create;<br />
var<br />
FDataset: TSdfDataset;<br />
begin<br />
inherited Create;<br />
<br />
FDataset := TSdfDataset.Create(nil);<br />
FDataset.FileName := vConfigurations.ComponentsDBFile;<br />
<br />
// Not necessary with TSdfDataset<br />
// FDataset.TableName := STR_DB_COMPONENTS_TABLE;<br />
// FDataset.PrimaryKey := STR_DB_COMPONENTS_ID;<br />
<br />
// Adds field definitions<br />
FDataset.FieldDefs.Add('ID', ftString);<br />
FDataset.FieldDefs.Add('NAMEEN', ftString);<br />
FDataset.FieldDefs.Add('NAMEPT', ftString);<br />
FDataset.FieldDefs.Add('HEIGHT', ftString);<br />
FDataset.FieldDefs.Add('WIDTH', ftString);<br />
FDataset.FieldDefs.Add('PINS', ftString);<br />
FDataset.FieldDefs.Add('DRAWINGCODE', ftString);<br />
<br />
// Necessary for TSdfDataset<br />
FDataset.Delimiter := ',';<br />
FDataset.FirstLineAsSchema := True;<br />
<br />
FDataset.Active := True;<br />
<br />
// Sets the initial record<br />
CurrentRecNo := 1;<br />
FDataset.First;<br />
end;</syntaxhighlight><br />
<br />
When using TSdfDataset directly be aware that RecNo, although it is implemented, does not work as a way to move through the dataset whether reading or writing records. The standard navigation routines like First, Next, Prior and Last work as expected, so you need to use them rather than RecNo.<br />
If you are used to using absolute record numbers to navigate around a database you can implement your own version of RecNo. Declare a global longint variable called CurrentRecNo which will hold the current RecNo value. Remember that this variable will have the same convention as RecNo, so the first record has number 1 (it is not zero-based). After activating the database initialize the database to the first record with TSdfDataset.First and set CurrentRecNo := 1<br />
<br />
<syntaxhighlight>{@@<br />
Moves to the desired record using TDataset.Next and TDataset.Prior<br />
This avoids using TDataset.RecNo which doesn't navigate reliably in any dataset.<br />
<br />
@param AID Indicates the record number. The first record has number 1<br />
}<br />
procedure TComponentsDatabase.GoToRec(AID: Integer);<br />
begin<br />
// We are before the desired record, move forward<br />
if CurrentRecNo < AID then<br />
begin<br />
while (not FDataset.EOF) and (CurrentRecNo < AID) do<br />
begin<br />
FDataset.Next;<br />
FDataset.CursorPosChanged;<br />
Inc(CurrentRecNo);<br />
end;<br />
end<br />
// We are after the desired record, move back<br />
else if CurrentRecNo > AID then<br />
begin<br />
while (CurrentRecNo >= 1) and (CurrentRecNo > AID) do<br />
begin<br />
FDataset.Prior;<br />
FDataset.CursorPosChanged;<br />
Dec(CurrentRecNo);<br />
end;<br />
end;<br />
end;</syntaxhighlight><br />
<br />
=== Using with data-aware controls ===<br />
<br />
== Lazarus and Advantage Database Server ==<br />
* Please see [[Advantage Database Server]] for details on using Advantage Database Server<br />
<br />
==See also==<br />
* [[Database_field_type]]<br />
* [[Databases]]<br />
* [[Databases in Lazarus]]<br />
* [[Firebird in action]]<br />
* [[How to write in-memory database applications in Lazarus/FPC]]<br />
* [[Lazarus DB Faq]]<br />
* [[Lazarus Tdbf Tutorial]]<br />
* [[MS Access]]<br />
* [[multi-tier_options_with_fpc|Multi-tier options with FPC]]<br />
* [[MySQLDatabases]]<br />
* [[ODBCConn]]<br />
* [[SQLdb Tutorial1]]<br />
* [[SqlDBHowto]]<br />
* [[SQLite]]<br />
* [[tiOPF]] - a free and open source Object Persistence Framework.<br />
* [[Zeos tutorial]]<br />
<br />
==External links==<br />
<br />
* [http://pdo.sourceforge.net Pascal Data Objects] - a database API that worked for both FPC and Delphi and utilises native MySQL libraries for version 4.1 and 5.0 and Firebird SQL 1.5, and 2.0. It's inspired by PHP's PDO class.<br />
* [http://lazaruszeos.blogspot.com Zeos+SQLite Tutorial] - Good tutorial using screenshots and screencasts it explain how to use SQLite and Zeos, spanish (google translate does a good work in translating it to english)<br />
<br />
<br />
[[Category:Databases]]<br />
[[Category:Tutorials]]</div>Mario13