Delphi - Creating A Database Application Using Delphi PDF
Delphi - Creating A Database Application Using Delphi PDF
Delphi - Creating A Database Application Using Delphi PDF
Borland
Kylix 3
COPYRIGHT 20012002 Borland Software Corporation. All rights reserved. All Borland brand and product names are trademarks or registered trademarks of Borland Software Corporation in the United States and other countries. All other marks are the property of their respective owners. K3-Delphi_DB-0702
Contents
Creating a database application using the Delphi IDE
Overview of database architecture . . . . Creating a new project . . . . . . . . . . . Setting up data access components . . . . Setting up the database connection . . Setting up the unidirectional dataset . Setting up the provider, client dataset, and data source . . . . . . . . . . . . Designing the user interface . . . . . . . . Creating the grid and navigation bar . Adding support for a menu . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 2 3 3 4 5 6 6 8 Adding a menu . . . . . . . . . . . . . . . Adding a button . . . . . . . . . . . . . . Displaying a title and an image . . . . . . . Writing an event handler . . . . . . . . . . . Writing the Update Now! command event handler . . . . . . . . . . . . . . . Writing the Exit command event handler Writing the FormClose event handler . . . . . . . 9 . 11 . 12 . 13
. . 13 . . 14 . . 14
Index
iii
iv
Chapter0
This tutorial guides you through the creation of an InterBase database application with which you can view and update a sample employee database. You will use the Delphi IDE to create the database application. This tutorial assumes you are familiar with Linux and have read the introduction to Kylix programming and the IDE in the Quick Start.
Note
This tutorial is written for the Kylix Enterprise and Professional editions, which include the database components. You must have InterBase installed to successfully complete this tutorial.
establishes a connection to the database. Each type of unidirectional dataset uses a different type of connection component.
Database application Data module
UI
Data source Client dataset
Connection component
Unidirectional dataset
Provider
Database server
For more information on database development, see Designing database applications in the Developers Guide or online Help.
1 Create a folder called Tutorial to hold the project files youll create while working through this tutorial. 2 Use the default project already created when you start the Delphi IDE or begin a new project by choosing File|New Application. 3 Choose File|Save All to save your files to disk. When the Save As dialog box appears, navigate to your Tutorial folder and save each file using its default name.
Later on, you can save your work at any time by choosing File|Save All. If you decide not to complete the tutorial in one sitting, you can open the saved version by choosing File|Reopen and selecting the tutorial from the list.
Tutorial
It is a good idea to isolate your user interface on its own form and house the data access components in a data module. However, to make things simpler for this tutorial, youll place the user interface and all the components on the same form.
1 Make sure the InterBase server has been started so that you can connect to the sample employee database used in this tutorial. For information about starting the server using the ibmgr utility, see the Interbase Operations Guide. 2 Click the dbExpress page on the Component palette and double-click the TSQLConnection component to place it on the form. To find the TSQLConnection component, point at an icon on the palette for a moment; a Help hint shows the name of the component. The component is called SQLConnection1 by default.
The TSQLConnection component is nonvisual, so it doesnt matter where you put it. However, for this tutorial, line up all the nonvisual components at the top of the form.
Tip
To display the captions for the components you place on a form, choose Tools| Environment Options|Designer and click Show component captions.
3 In the Object Inspector, set the ConnectionName property to IBConnection (its on the drop-down list). 4 Set the LoginPrompt property to False. By setting this property to False, you wont be prompted to log on every time you access the database. 5 Double-click the TSQLConnection component to display the Connection editor.
You use the Connection editor to select a connection configuration for the TSQLConnection component or edit the connections stored in the dbxconnections file in the .borland directory. In the Connection editor, specify the pathname of the database file called employee.gdb on your system. In this tutorial you will connect to a sample InterBase database, employee.gdb, that is provided with Kylix. By default, the InterBase installation places employee.gdb in /opt/interbase/examples.
You can choose from several database drivers to connect to your database and then edit the connection settings. You can add, delete, rename, and test your connections.
6 Check the User_Name and Password fields for acceptable values. If you have not altered the default values, you do not need to change the fields. If database access is administered by someone else, you may need to get a username and password to access the database. 7 When you are done checking and editing the fields, click OK to close the Connection editor and save your changes.
These changes are written to the dbxconnections file and the selected connection is assigned as the value of the SQLConnection components ConnectionName property.
1 From the dbExpress page, drop TSQLDataSet at the top of the form. 2 In the Object Inspector, set its SQLConnection property to SQLConnection1 (the database connection created previously).
Tutorial
3 Set the CommandText property to Select * from sales to specify the command that the dataset executes. You can either type the Select statement in the Object Inspector or click the ellipsis to the right of CommandText to display the CommandText editor, where you can build your own query statement. 4 Set Active to True to open the dataset. 5 Choose File|Save All to save the project.
1 From the Data Access page, drop a TDataSetProvider component at the top of the form. 2 In the Object Inspector, set the providers DataSet property to SQLDataSet1.
The client dataset buffers its data in memory. It also caches updates to be sent to the database. You can use client datasets to supply the data for data-aware controls on the user interface using the data source component. To add the client dataset:
1 From the Data Access page, drop a TClientDataSet component to the right of the TDataSetProvider component. 2 Set the ProviderName property to DataSetProvider1. 3 Set the Active property to True to allow data to be passed to your application.
A data source connects the client dataset with data-aware controls. Each data-aware control must be associated with a data source component to have data to display and manipulate. Similarly, all datasets must be associated with a data source component for their data to be displayed and manipulated in data-aware controls on a form. To add the data source:
1 From the Data Access page, drop a TDataSource component to the right of the TClientDataSet component. 2 Set the data sources DataSet property to ClientDataSet1. 3 Choose File|Save All to save the project.
So far you have added the nonvisual database infrastructure to your application. Next you need to design the user interface.
1 You can start by adding a grid to the form. From the Data Controls page, drop a TDBGrid component onto the form. 2 Set DBGrids properties to anchor the grid. Click the + next to Anchors in the Object Inspector to display akLeft, akTop, akRight, and akBottom; set them all to True. The easiest way to do this is to double-click False next to each property in the Object Inspector. 3 Align the grid with the bottom of the form by setting the Align property to alBottom. You can also enlarge the size of the grid by dragging it or setting its Height property to 400. 4 Set the grids DataSource property to DataSource1. When you do this, the grid is populated with data from the employee database. If the grid doesnt display data, make sure youve correctly set the properties of all the objects on the form, as explained in previous instructions.
So far your application should look like this:
Tutorial
The DBGrid control displays data at design time, while you are working in the IDE. This allows you to verify that youve connected to the database correctly. You cannot, however, edit the data at design time; to edit the data in the table, youll have to run the application.
5 From the Data Controls page, drop a TDBNavigator control onto the form. A database navigator is a tool for moving through the data in a dataset (using next and previous arrows, for example) and performing operations on the data. 6 Set the navigator bars DataSource property to DataSource1 so the navigator is looking at the data in the client dataset. 7 Set the navigator bars ShowHint property to True. (Setting ShowHint to True allows Help hints to appear when the cursor is positioned over each of the items on the navigator bar at runtime.) 8 Choose File|Save All to save the project. 9 Press F9 to compile and run the project. You can also run the project by clicking the Run button on the Debug toolbar, or by choosing Run from the Run menu.
When you run your project, the program opens in a window like the one you designed on the form. You can test the navigation bar with the employee database. For example, you can move from record to record using the arrow commands, add records using the + command, and delete records using the command.
Tip
If you should encounter an error while testing an early version of your application, choose Run|Program Reset to return to the design-time view.
1 If the application is still running, click the X in the upper right corner to close the application and return to the design-time view of the form. 2 From the Common Controls page of the Component palette, drop an ImageList component onto the form. Line this up next to the other nonvisual components. The ImageList will contain icons that represent standard actions like cut and paste. 3 From the Standard page of the Component palette, drop an ActionList component onto the form. Set the action lists Images property to ImageList1. 4 Double-click the action list to display the Action List editor. 5 Right-click the Action List editor and choose New Standard Action. The Standard Actions list box appears.
Right-click in the editor and choose New Standard Action to display the Standard Actions list box. Select the actions you want and click OK. Press Ctrl to select multiple actions.
6 Select the following actions: TEditCopy, TEditCut, and TEditPaste. (Use the Ctrl key to select multiple items.) Then click OK.
These standard actions appear in the Action List editor with default images already associated with them.
Youve added three standard actions that come with the product. Youll use these on a menu.
Tutorial
7 Right-click the Action List editor and choose New Action to add another action (not provided by default). Action1 is added by default. In the Object Inspector, set its Caption property to Update Now!
This same action will be used on a menu and a button. Later on, youll add an event handler so it will update the database.
8 Click (No Category), right-click and choose New Action to add another action. Action2 is added. Set its Caption property to E&xit. 9 Click the X (in the upper right corner) to close the Action List editor.
Youve added three standard actions plus two other actions that youll connect to event handlers later.
Adding a menu
In this section, youll add a main menu bar with two drop-down menusFile and Editand youll add menu items to each one using the actions in the action list.
1 From the Standard page of the Component palette, drop a TMainMenu component onto the form. Drag it next to the other nonvisual components. 2 Set the main menus Images property to ImageList1 to associate the image list with the menu items. 3 Double-click the TMainMenu component to display the Menu Designer.
4 Type &File to set the Caption property of the first top-level menu item and press Enter.
When you type &File and press Enter, the top-level File command appears ready for you to add the first menu item. The ampersand before a character activates an accelerator key.
5 Select the blank menu item below the File menu. Set the blank menu items Action property to Action2. An Exit menu item appears under the File menu. 6 Click the second top-level menu item (to the right of File). Set its Caption property to &Edit and press Enter. Select the blank menu item that appears under the Edit menu. 7 In the Object Inspector, set the Action property to EditCut1 and press Enter. The items caption is automatically set to Cut and a default cut bitmap appears on the menu. 8 Select the next blank menu item (under Cut) and set its Action property to EditCopy1 (a default copy bitmap appears on the menu). 9 Select the next blank menu item (under Copy) and set its Action property to EditPaste1 (a default paste bitmap appears on the menu). 10 Select the next blank menu item (under Paste) and set its Caption property to a hyphen (-) to create a divider line in the menu. Press Enter. 11 Select the next blank menu item (under the divider line) and set its Action property to Action1. The menu item displays Update Now! 12 Click the X to close the Menu Designer. 13 Choose File|Save All to save the project.
10
Tutorial
14 Press F9 or Run on the toolbar to run your program and see how it looks.
Many of the commands on the Edit menu and the navigation bar are operational at this time. Copy and Cut are grayed on the Edit menu until you select some text in the database. You can use the navigation bar to move from record to record in the database, insert a record, or delete a record. The Update command does not work yet. Close the application when youre ready to continue.
Adding a button
This section describes how to add an Update Now button to the application. This button is used to apply any edits that a user makes to the database, such as editing records, adding new records, or deleting records. To add a button:
1 From the Standard page of the Component palette, drop a TButton onto the form. (Select the component then click the form next to the navigation bar.) 2 Set the buttons Action property to Action1.
The buttons caption changes to Update Now! When you run the application, it will be grayed out until an event handler is added to make it work.
11
1 From the Standard page of the Component palette, drop a TLabel component onto the form. Kylix names this Label1 by default. 2 In the Object Inspector, change the labels Caption property to World Corp or another company name. 3 Change the company names font by clicking the Font property. Click the ellipsis that appears on the right and in the Font dialog box, change the font to Helvetica Bold, 16-point type. Click OK.
You can change the font of the label using the Font property in the Object Inspector. Click the ellipsis to display a standard font dialog box.
4 Position the label in the upper right corner. 5 From the Additional page of the Component palette, drop a TImage component next to the label. Kylix names the component Image1 by default. 6 To add an image to the Image1 component, click the Picture property. Click the ellipsis to display the Picture editor. 7 In the Picture editor, choose Load and navigate to the icons directory provided with the product. The default location is {install directory}/images/icons. For example, if Kylix is installed in your /usr/local/kylix directory, look in /usr/ local/kylix/images/icons. 8 Double-click earth.ico. Click OK to load the picture and to close the Picture editor.
12
Tutorial
9 Size the default image area to the size of the picture. Place the image next to the label.
You can set the size of the Image1 component to match the size of the picture inside it in two ways: drag the edge of Image1, or change the Width and Height properties in the Object Inspector.
10 To align the text and the image, select both objects on the form, right-click, and choose Align. In the Alignment dialog box, under Vertical, click Bottoms. 11 Choose File|Save All to save the project. 12 Press F9 to compile and run your application. 13 Close the application when youre ready to continue.
1 Double-click the ActionList component to display the Action List editor. 2 Select (No Category) to see Action1 and Action2.
13
3 Double-click Action1. In the Code editor, the following skeleton event handler appears:
procedure TForm1.Action1Execute(Sender: TObject); begin end;
Right where the cursor is positioned (between begin and end), type:
if ClientDataSet1.State in [dsEdit, dsInsert] then ClientDataSet1.Post; ClientDataSet1.ApplyUpdates(-1);
This event handler first checks to see what state the database is in. When you move off a changed record, it is automatically posted. But if you dont move off a changed record, the database remains in edit or insert mode. The if statement posts any data that may have been changed but was not passed to the client dataset. The next statement applies updates held in the client dataset to the database.
Note
Changes to the data are not automatically posted to the database when using dbExpress. You need to call the ApplyUpdates method to write all updated, inserted, and deleted records from the client dataset to the database.
1 Double-click the ActionList component to display the Action List editor if it is not already displayed. 2 Click (No Category) so you see Action2. 3 Double-click Action2. The Code editor displays the following skeleton event handler:
procedure TForm1.Action2Execute(Sender: TObject); begin end;
Right where the cursor is positioned (between begin and end), type:
Close;
This event handler will close the application when the File|Exit command on the menu is used.
4 Close the Action List editor. 5 Choose File|Save All to save the project.
14
Tutorial
1 Click the grid area of the main form to select the form itself. 2 Select the Events tab in the Object Inspector to see the form events. 3 Double-click OnClose (or type FormClose next to the OnClose event and click it). A skeleton FormClose event handler is written and displayed in the Code editor after the other event handlers:
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); begin end; Right where the cursor is positioned (between begin and end), type: Action := caFree; if ClientDataSet1.State in [dsEdit, dsInsert] then ClientDataSet1.Post; if ClientDataSet1.ChangeCount> 0 then begin Option := Application.MessageBox('You have pending updates. Do you want to write them to the database?', 'Pending Updates',[smbYes, smbNo, smbCancel], smsWarning, smbYes); case Option of smbYes: ClientDataSet1.ApplyUpdates(-1); smbCancel: Action := caNone; end; end;
This event handler checks the state of the database. If changes are pending, they are posted to the client dataset where the change count is increased. Then before closing the application, a message box is displayed that asks how to handle the changes. The reply options are Yes, No, or Cancel. Replying Yes applies updates to the database; No closes the application without changing the database; and Cancel cancels the exit but does not cancel the changes to the database and leaves the application still running.
4 You need to declare the variable used within the procedure. On a line between procedure and begin type:
var Option: TMessageButton;
15
6 To finish up, choose File|Save All to save the project. Then press F9 to run the application.
Tip
Fix any errors that occur by double-clicking the error message to go to the code in question or by pressing F1 for Help on the message. Thats it! You can try out the application to see how it works. When you want to exit the program, you can use the fully functional File|Exit command.
16
Tutorial
Index
A
ActionList component 8 adding a database connection to an application 3 a grid to an application 6 a menu to an application 8 to 11 a title to an application 12 an image to an application 12 an Update Now button to an application 11 unidirectional dataset component 4 applying edits to database 11
D
database applications accessing 3 to 4 overview 1 database sample, employee.gdb 4 database user name and password 4 DataSetProvider component 5 datasets client 5 unidirectional 4 DataSource component 5 dbExpress 1 DBGrid component 6 DBNavigator component 7
B
Button component 11 button, adding Update Now 11
E
employee.gdb sample database 4 event handlers, creating 13 to 16 events 13
C
ClientDataSet component 5 code, writing 13 to 16 compiling programs 7 components ActionList 8 Button 11 ClientDataSet 5 DataSetProvider 5 DataSource 5 DBGrid 6 DBNavigator 7 Image 12 ImageList 8 Label 12 MainMenu 9 nonvisual 3 SQLConnection 3 SQLDataSet 3 connection component, adding 3 creating a project 2
G
grid, adding to an application 6
I
ibmgr utility 3 icons, adding to application 12 Image component 12 image, adding to application 12 ImageList component 8 Interbase server, starting 3
L
Label component 12
M
MainMenu component 9 menu, adding to an application 8 to 11
Index
N
navigating data in the dataset 7 nonvisual components 3
S
sample database 4 SQLConnection component 3 SQLDataSet component 3
P
password for database 4 project creating 2 running 7
T
title, adding to application 12
U
unidirectional dataset 4 updating a database 11 user name for database 4
R
running applications 7
vi
Tutorial