📄 ch18.htm
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN"><HTML><HEAD><SCRIPT LANGUAGE="JavaScript"><!--function popUp(pPage) { var fullURL = document.location; var textURL = fullURL.toString(); var URLlen = textURL.length; var lenMinusPage = textURL.lastIndexOf("/"); lenMinusPage += 1; var fullPath = textURL.substring(0,lenMinusPage); popUpWin = window.open('','popWin','resizable=yes,scrollbars=no,width=525,height=394'); figDoc= popUpWin.document; zhtm= '<HTML><HEAD><TITLE>' + pPage + '</TITLE>'; zhtm += '</head>'; zhtm += '<BODY bgcolor="#FFFFFF">'; zhtm += '<IMG SRC="' + fullPath + pPage + '">'; zhtm += '<P><B>' + pPage + '</B>'; zhtm += '</BODY></HTML>'; window.popUpWin.document.write(zhtm); window.popUpWin.document.close(); // Johnny Jackson 4/28/98 }//--> </SCRIPT><link rel="stylesheet" href="/includes/stylesheets/ebooks.css"> <META HTTP-EQUIV="Content-Type" CONTENT="text/html;CHARSET=iso-8859-1"> <TITLE>Teach Yourself Borland Delphi 4 in 21 Days -- Ch 18 -- Building Database Applications</TITLE></HEAD><BODY TEXT="#000000" BGCOLOR="#FFFFFF"><CENTER><H1><IMG SRC="../button/sams.gif" WIDTH="171" HEIGHT="66" ALIGN="BOTTOM" BORDER="0"></H1></CENTER><CENTER><H1><BR>Teach Yourself Borland Delphi 4 in 21 Days</H1></CENTER><CENTER><P><A HREF="../ch17/ch17.htm"><IMG SRC="../button/previous.gif" WIDTH="128" HEIGHT="28"ALIGN="BOTTOM" ALT="Previous chapter" BORDER="0"></A><A HREF="../ch19/ch19.htm"><IMGSRC="../button/next.gif" WIDTH="128" HEIGHT="28" ALIGN="BOTTOM" ALT="Next chapter"BORDER="0"></A><A HREF="../index.htm"><IMG SRC="../button/contents.gif" WIDTH="128"HEIGHT="28" ALIGN="BOTTOM" ALT="Contents" BORDER="0"></A> <HR></CENTER><CENTER><H1>- 18 -</H1></CENTER><CENTER><H1>Building Database Applications</H1></CENTER><UL> <LI><A HREF="#Heading1">Nonvisual Database Programming</A> <UL> <LI><A HREF="#Heading2">Reading from a Database</A> <LI><A HREF="#Heading3">Creating a Database in Code</A> <LI><A HREF="#Heading4">Creating the Field Definitions</A> </UL> <LI><A HREF="#Heading5">Using Data Modules</A> <UL> <LI><A HREF="#Heading6">Setting Up a Sample Data Module</A> <LI><A HREF="#Heading7">Adding to Your Data Module</A> <LI><A HREF="#Heading8">Running the Data Module</A> </UL> <LI><A HREF="#Heading9">Creating Reports</A> <UL> <LI><A HREF="#Heading10">QuickReport Overview</A> <LI><A HREF="#Heading11">The QuickRep Component</A> <LI><A HREF="#Heading12">Report Bands</A> <LI><A HREF="#Heading13">Creating Reports by Hand</A> <LI><A HREF="#Heading14">Creating Reports the Easy Way</A> </UL> <LI><A HREF="#Heading15">Deploying a Delphi Database Application</A> <LI><A HREF="#Heading16">Summary</A> <UL> <LI><A HREF="#Heading17">Q&A</A> <LI><A HREF="#Heading18">Quiz</A> <LI><A HREF="#Heading19">Exercises</A> </UL></UL><P><HR SIZE="4"><CENTER><H1></H1></CENTER><P>This chapter is about building database applications. The truth is, I cannot tellyou everything there is to know about writing database applications in one shortchapter. What I can do is point out some issues you are likely to encounter whenwriting database applications.</P><P>Because you already know how to create database forms, you will spend most ofthis day dealing with lower level aspects of database programming. You'll start withcreating and populating a database entirely through code, and then you'll move onto data modules. Toward the end of the day you'll look at creating database reportswith the QuickReport components. Finally, the day ends with a discussion on deployingdatabase applications.</P><P><H2><A NAME="Heading1"></A>Nonvisual Database Programming</H2><P>Up to this point, you have examined almost exclusively the visual aspects of databaseprogramming with Delphi. That side of database programming is fun and easy, but sooneror later you have to do some real database programming. The kinds of programs youhave written so far have dealt primarily with simple viewing and editing of data.In this section, you learn how to perform certain database operations through code.</P><BLOCKQUOTE> <P><HR><strong>TIP:</strong> I will mention only database operations that pertain to the TTable class. You could also use SQL to perform database operations in code, but I won't present that aspect of databases today. <HR></BLOCKQUOTE><H3><A NAME="Heading2"></A>Reading from a Database</H3><P>This section is short because reading from an existing database isn't difficult.As an example exercise, you will take the CUSTOMER.DB table and create a comma-delimitedtext file from the data. You won't write every field in the table to the file, butyou'll write most of them.</P><P>The first step is to create a TTable object. Next, attach it to a database andto a particular table within the database. Here's how the code looks:</P><P><PRE>var Table : TTable;begin Table := TTable.Create(Self); Table.DatabaseName := `DBDEMOS'; Table.TableName := `Customer.db';end;</PRE><P>This code emulates what Delphi does when you set the DatabaseName and TableNameproperties at design time. The next step is to read each record of the database andwrite it to a text file. First, I'll show you the basic structure without the actualcode to write the fields to the text file. After that, I'll be more specific. Thebasic structure looks like this:</P><P><PRE>Table.Active := True;while not Table.Eof do begin { Code here to read some fields from the } { current record and write them to a text file. } Table.Next;end;Table.Free;</PRE><P>This code is straightforward. First, the table is opened by setting the Activeproperty to True (you could also have called the Open method). Next, a while loopreads each record of the table. When a record is written to the text file, the Nextmethod is called to advance the database cursor to the next record. The while loop'scondition statement checks the Eof property for the end of the table's data and stopsthe loop when the end of the table is reached. Finally, the TTable object is freedafter the records have been written to the text file.</P><BLOCKQUOTE> <P><HR><strong>NOTE:</strong> You don't specifically have to delete the TTable object. When you create a TTable object in code, you usually pass the form's Self pointer as the owner of the object--for example, <HR></BLOCKQUOTE><PRE>Table := TTable.Create(Self);</PRE><P>This sets the form as the table's owner. When the form is deleted, VCL will automaticallydelete the TTable object. For a main form this happens when the application is closed.Although you are not required to delete the TTable object, it's always a good ideato delete the object when you are done with it.</P><P>Naturally, you need to extract the information out of each field in order to writeit to the text file. To do that, you use the FieldByName method and the AsStringproperty of TField. I addressed this briefly on Day 16, "Delphi Database Architecture,"in the section "Accessing Fields." In the CUSTOMER.DB table, the firstfield you want is the CustNo field. Extracting the value of this field would looklike this:</P><P><PRE>var S : string;begin S := Table.FieldByName(`CustNo').AsString + `,';</PRE><P>Notice that a comma is appended to the end of the string obtained so that thisfield's data is separated from the next. You will repeat this code for any fieldsfor which you want to obtain data. The entire sequence is shown in Listings 18.1and 18.2. These listings contain a program called MakeText, which can be found withthe book's code. This short program takes the CUSTOMER.DB table and creates a comma-delimitedtext file called CUSOMTER.TXT. Listing 18.1 shows the main form's unit (MakeTxtU.pas).The form contains just a button and a memo. Look over these listings, and then I'lldiscuss how the program works.</P><P><H4>LISTING 18.1. MakeTxtU.pas.</H4><PRE>unit MakeTxtU;interfaceuses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, ÂDialogs, StdCtrls, DbTables;type TForm1 = class(TForm) CreateBtn: TButton; Memo: TMemo; procedure CreateBtnClick(Sender: TObject); private { Private declarations } public { Public declarations } </PRE><PRE> end;</PRE><PRE>var Form1: TForm1;implementation{$R *.DFM} procedure TForm1.CreateBtnClick(Sender: TObject);var Table : TTable; S : string;begin { Create the Table and assign a database and Table name. } Table := TTable.Create(Self); Table.DatabaseName := `DBDEMOS'; Table.TableName := `Customer.db'; { Change to the busy cursor. } Screen.Cursor := crHourGlass; { We can use a Memo to show the progress as well as to } { save the file to disk. First clear the memo of any text.} Memo.Lines.Clear; { Open the Table. } Table.Active := True; CreateBtn.Enabled := False; { Loop through the records, writing each one to the memo. } while not Table.Eof do begin { Get the first field and add it to the string S, } { followed by the delimiter. } S := Table.FieldByName(`CustNo').AsString + `,'; { Repeat for all the fields we want. } S := S + Table.FieldByName(`Company').AsString + `,'; S := S + Table.FieldByName(`Addr1').AsString + `,'; S := S + Table.FieldByName(`Addr2').AsString + `,'; S := S + Table.FieldByName(`City').AsString + `,'; S := S + Table.FieldByName(`State').AsString + `,'; S := S + Table.FieldByName(`Zip').AsString + `,'; S := S + Table.FieldByName(`Phone').AsString + `,'; S := S + Table.FieldByName(`FAX').AsString; { Add the string to the Memo. } Memo.Lines.Add(S); { Move to the next record. } Table.Next; end; { Write the file to disk. } Memo.Lines.SaveToFile(`customer.txt'); { Turn the button back on and reset the cursor. } CreateBtn.Enabled := True; Screen.Cursor := crDefault; Table.Free;end;end.</PRE><PRE>All the action takes place in the CreateBtnClick method. When you click the Create File button, the program extracts data from the database table and puts it into the Memo component. First, the value of the CustNo field is read and put into a string, followed by a comma. After that, each subsequent field's value is appended to the end of the string, again followed by a comma. After all the data has been extracted from a record, the string is added to the memo, using the Add method. When the end of the table is reached, the memo contents are saved to disk.</PRE><P>I used a Memo component in this example for two reasons. First, by displayingthe results in a memo, you can see what the program produces. Second, the memo component'sLines property (a TStrings) provides an easy way of saving a text file to disk. Figure18.1 shows the MakeText program after the file has been written.</P><P><A HREF="javascript:popUp('28671801.gif')"><B>FIGURE 18.1.</B></A><B> </B><I>TheMakeText program running.</I></P><P><H3><A NAME="Heading3"></A>Creating a Database in Code</H3><P>Most of what you read on database operations in Delphi tells you how to createa database with utilities such as Database Desktop. That's fine if your applicationhas pre-built tables. But if your application has to dynamically create tables, thatapproach doesn't work. You must have a way of creating tables through code. For example,if your application enables users to specify the fields of a table, you won't knowwhat the fields are until the user has supplied them.</P><P>Creating a table in code requires these steps:</P><DL> <DT></DT> <DD><B>1. </B>Create a BDE alias for the database. <P> <DT></DT> <DD><B>2. </B>Create a TTable object. <P> <DT></DT> <DD><B>3. </B>Add field definitions to the FieldDefs property. <P> <DT></DT> <DD><B>4. </B>Add index definitions to the IndexDefs property if your table contains indexes.</DL><BLOCKQUOTE> <P> <P><B>5. </B>Create the actual table with the CreateTable method.</BLOCKQUOTE><PRE></PRE><P>Let's go over these steps individually so that you know what each step involves.</P><P><H4>Creating a BDE Alias and a TTable Object</H4><P>You already performed steps 1 and 2 on Day 16 when I talked about creating a BDEalias, and you created a TTable object in the preceding section. Here's a recap of
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -