Presentation is loading. Please wait.

Presentation is loading. Please wait.

Rapid Applications Programming with Windows Week 10.

Similar presentations


Presentation on theme: "Rapid Applications Programming with Windows Week 10."— Presentation transcript:

1 Rapid Applications Programming with Windows Week 10

2 Topics Week 10 zThe Borland Database Engine (BDE) zDatabase Desktop zAn Overview of Delphi Database Components zUsing the Database Form Wizard yData Modules zCreating Database Forms by Hand yData components ySearching for Records

3 The Borland Database Engine (BDE) zProvides access to local, client/server databases ylocal: (single-tier) all data manipulation occurs immediately yClient/server, two-tier: xclient application talks to the database server through database drivers xDatabase server manages connections xclient application is responsible for managing the integrity of the data (validation etc)

4 The Borland BDE... zClient/Server, MultiTier yClient application talks to one or more application Servers, which in turn talk to the database server yApplication servers are specialised e.g. data broker, security handler yclient app. may be little more than the interface (Thin-client apps). Can be programmed by ‘juniors’ zBDE Drivers vary a/c Delphi version ySTANDARD driver provides access to Paradox, dBase yOther drivers provided for e.g. Sybase, Oracle, Informix, InterBase, MSAccess95, 97,( NOT 2000) Excel, FoxPro

5 The Borland BDE... zThe BDE Administrator utility yThe Database Page (tab) xdisplays list of all available DB aliases xan alias provides the path to a DB, and specifies the driver to use xjust change the alias path when changing PC’s xAll Delphi database access routines will reference the DB alias, which then references the DB tables xObject|New to create a new alias, then click ‘Apply’ speed button (or Code Examp1) xSave Table As (in Database Desktop) also displays a list of available aliases

6 The Borland BDE... zThe BDE Administrator utility (contd) yThe Configuration Page (tab) xConfigure the installed drivers: Native, ODBC xChange e.g. Block Size, StrictIntegrity, Fill Factor xAdd new ODBC driver xChange settings for the System Object: INIT settings (for starting an app, stored in Windows Registry) Formats settings e.g. Date, Time, Number

7 Database Desktop zTools|Database Desktop from within Delphi,(or select as a stand-alone application) Create a New Table with Database Desktop: zFile|New Table yChoose Database table type (e.g. Paradox 7) yTable details specifications dialog: xData Type: autoIncrement, Date, Time, Money, OLE xValidity Checks: required, Min/max values, default xsecondary indexes xreferential integrity xpassword access to the field

8 Database Desktop... zFile|Open|Table, then choose alias to a database (e.g. DBDEMOS), then the table zTable|Edit Data to change, add data zTable|Restructure to change table definitions zFile|Working Directory to specify directory where the database lives zTools/Alias Manager to change, create aliases (as in BDE Administrator)

9 Delphi Database Components zNon-Visual data access components yDerived from TDataSet class yprovide mechanism to get at the data via specific properties: xTTable: DatabaseName, TableName xTQuery: DatabaseName, SQL xTStoredProc: DatabaseName, StoredProcName zVisual data-aware components (controls) yenable user to view, edit the data yTDBEdit, TDBListBox, TDBImage, TDBGrid etc zTDataSet components and visual controls communicate via a TDataSource component.

10 Database Form Wizard zFile|New|Business Page ->DataBase Form Wizard OR Database|Form Wizard zChoose between a simple or master/detail form zSpecify Table, fields, layout for Master info zSame for Detail information (use Grid layout) plus ‘link’ fields (usually the foreign key) zRun the project, using the Database Navigator control (similar to the VB Data Control) to access the records. zMay need to change component type e.g. an OLE object is displayed as a DBEdit field zUse the form as a starting point, then customise

11 Database Form Wizard zOn the final screen, Form Generation -> Form and DataModule option will store the Dataset component (TTable or TQuery) and the DataSource in a separate module. yAllows reuse of those data access specifications: File|Use Unit DataMod.pas yCan also create a Data Module ‘by hand’ via File|New -> Data Module yIn the Data Module’s On Create event handler open the dataset(s) it contains e.g. xCustTable.Open

12 Database Forms, ‘by Hand’ zTo display data from >1 table, cut/paste all the database components from a ‘wizard-created’ second form to the first form created Building forms without the Database Wizard zStart with a TDataset object (TTable or TQuery) yTQuery allows SQL to be written, specifying tables, and fields to be selected ySet its DatabaseName (via an alias), then TableName (for a TTable), or SQL statement (for a TQuery) zAdd a RecordSource Object, and point its Dataset property to the TTable/TQuery

13 Database Forms, ‘By Hand’... zPlace appropriate data-aware controls on the form from the Data Controls page (tab) on the component palette zSet their DataSource, DataField properties zSet the Active property of the TTable component to True to see the data at design time (do this last) zBy default, Delphi creates a TField object for each field in the DataSet at run-time. You can create these at design time, specifying which fields are to be included in the DataSet, and set their properties: very useful with a DBGrid zRight-click the DataSet object (TTable, TQuery), then Fields Editor

14 Database Forms, ‘By Hand’… The Fields Editor zRight-click, then Add Fields, and select all the fields from the DataSet which you want to use in your application zSelect a field in the Field Editor, to set its properties in the Object Inspector e.g.DisplayLabel, Visible, EditMask, DisplayFormat etc (note the TField component types). zNote that a DBGrid can’t display a BLOB type, so set Visible to False (still available, not visible) Create new, calculated fields, based on values from the DataSet: zRight-click the Fields Editor, choose New Field zEnsure Field Type option button Calculated is selected

15 Database Forms, ‘By Hand’… The Fields Editor zCode for the OnCalcFields event (of a DataSet component) (Example 2) zThe TTable Object will call the procedure once for each record, so the calculated field will appear for each record in the DBGrid zLookup fields allow you to place a drop-down list in the grid: limit user to a set of choices determined by a DataSet component zCreate a new DataSet component (TTable/TQuery) to be the SOURCE of the data for the drop-down list

16 Database Forms, ‘By Hand’… The Fields Editor zIn the New Field Dialog from the Fields Editor, select Lookup as the field type zSet DataSet to the dataset where the data is COMING FROM zKey Fields e.g. SupplierID in the Stock Table will be used to lookup the SupplierName (Result Field) in the Supplier Table (DataSet), via the SupplierID (LookupKeys) in the Supplier table. zSo when the user chooses a supplier name from the drop-down list, its corresponding SupplierID is written to the Stock table when record is updated.

17 Database Forms, ‘By Hand’... zFinally, make the original DBGrid field (i.e. SupplierID) not visible zTo replicate this on another page with a SupplierID, remove the original DBEdit field (which displayed SupplierID), then drag the SupplierLookup field from the Field Editor to the form zEach TField Object has a Validation Event (Example 3) zFilter the Table component records (like a Where clause) ySet Filtered to True ySpecify the filter: CustNumber = 1234 AND ShipDate < ‘1/1/98’

18 Database Forms, ‘By Hand’… Finding a Record zFinding Records in a DataSet (Example 4) yUse the FindNearest method (only with a TTable component) for an approximate search. Positions the cursor on the first record that matches the criteria, or on the first record whose values are greater than those specified yUse the FindKey Method for an exact match yBoth FindNearest and FindKey require IndexName to be set before the search yLocate Method uses an index if available, otherwise searches sequentially yFindKey, Locate return true/false, and position the cursor on the record if found

19 Database Forms ‘By Hand’… Referencing dataset records zThe TField class represents a field in the database, gives access to its attributes yFieldByName Method accesses the field yset field’s value with AsString, AsInteger, etc or Value Table1.FieldByName(‘LastName’).AsString := Edit1.Text; OR Table1.FieldByName(‘LastName’).Value := Edit1.Text; yTo Change a field’s value: Table1.Edit; Table1.FieldByName(‘LastName’).AsString := Edit1.Text; Table1.Post;

20 Database Forms, ‘By Hand’… Data-aware Components Data-aware Components zUse the ‘Field’ property to access the contents, display NameEdit.Field.AsString := ‘Clown Fish’; zDBGrid yuse the Columns property to change the display yOptions property controls behaviour e.g col. Sizing zDBText: Label, DBEdit: Edit Box zDBMemo: Memo ydisplay large text fields yIf AutoDisplay is False, Double-click to display the data

21 Database Forms, ‘By Hand’… Data-aware Components zDBImage: ydisplay binary large object data stored in image format ychange via Clipboard at design, run-time or via code: DBImage1.Picture.LoadFromFile(‘clouds.bmp’); zDBListBox, DBComboBox yitems for selection are specified via the Items property ywhen an item is selected, it is written to the DataField field in the DataSet zDBCheckBox yDBCheckBox1.ValueChecked := ‘On;Yes;True’;

22 Database Forms, ‘By Hand’… Data-aware Components zDBLookupListBox, DBLookupComboBox yDisplays a list of values from a lookup field in a dataset: ListSource, ListField yWhen an item is selected, its value is written to another field in another dataset: DataSource, DataField zDBCtrlGrid ycreate custom scrollable grid components yplace any data components on the first cell of the grid, and Delphi will duplicate those components for each record in the dataset at run-time

23 Database Forms, ‘By Hand’… Data-aware Components zDBNavigator yAllows extensive manipulation of dataset records yfirst, next, previous, last, insert, delete, edit, cancel edits, post edits, refresh yConfirmDelete, VisibleButtons property yAdd, remove buttons at design, run-time (Examp. 5) ysimulate a DBNavigator button-click (Example 6) zDisplay fly-over help ySet ShowHint property to True yUse the Hints property String list editor to enter a separate line of hint text for each button

24 Database Forms, ‘By Hand’… Dataset programming zProviding Default Values, Appending via Code yThe DataSet event OnNewRecord fires when an app. inserts or appends a new record into a dataset. yinsert your own ‘next’ primary key, today’s date etc procedure TForm1.Button1Click(Sender: TObject); begin Table1.Append; //create a new record Table1.FieldByName(‘Name’).AsString := Edit1.text; Table1.FieldByName(‘Age’).AsInteger := StrToInt(Edit2.text); Table1.Post; end;

25 TQuery Components zUse ExecSQL for SQL statements which do not return records: Query1.SQL.Clear; Query1.SQL.Add(‘insert into CountryTable’); Query1.SQL.Add(‘ (Name, Capital) ‘); Query1.SQL.Add(‘ (values (“Australia”, “Canberra”) ’); Query1.ExecSQL; zCan also build up the query as a string, then ‘Add’ the whole string var query: string query := query + ‘Select * from Orders where ‘; etc

26 TQuery Components Using Parameters in SQL statements: zAt design time, the SQL statement is select * from CountryTable where name = :ParCountry zAt run-time e.g. OnChange event of the edit control With Query1 do begin DisableControls; Close; ParamByName(‘ParCountry’).AsString := edtCountry.Text; Open; EnableControls; end;

27 TQuery components zUse the Datasource property to automatically link to another datasource and access any matched- name fields, which can be used as parameters in the SQL for the Query. zUseful in master/detail forms. E.g. ytable1/ds1 accesses the customer table, yquery1/ds2 retrieves orders which match the custno of the ‘current’ customer record: (custno is a foreign key in the orders table) yset the Datasource of the Query to point to ds1: custno becomes the parameter for the query e.g. select * from orders, customer where orders.custno = customer.custno

28 Dataset Programming zDisable the data-aware controls when making changes or performing long operations on the dataset (e.g. loop) zUse a bookmark to keep track of where you started in the dataset zUse a try-finally block to catch exceptions that may occur when reading table data zSee Example 8

29 Tutorial Week 10 zUse the tute exercises to become familiar with Delphi 5 zStart Delphi Assignment Task 1 (create Paradox DB tables, add data) zStart Delphi Assignment Task 3 yBegin with the Database Form Wizard yAdd, customise to meet task requirements zNote: Because of limited availability of Delphi 5 (K1.07, K1.08, K1.10, B3.46, B3.43, B3.43B, T2.16), and since most of you will not have the software at home, tutes will be used to work on the weekly assignment tasks. zThe remaining 4 Tute Exercise marks will be added to the Delphi Assignment, which will now be /14


Download ppt "Rapid Applications Programming with Windows Week 10."

Similar presentations


Ads by Google