⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ch18.htm

📁 delphi自学的好教材!特别适合刚刚起步学习delphi的人员!同样对使用者具有参考价值!
💻 HTM
📖 第 1 页 / 共 4 页
字号:
those two steps:</P><P><PRE>var  Table : TTable;begin  { Create the alias. }   CreateDirectory(`c:', nil);  Session.AddStandardAlias(`MyDatabase', `c:', `PARADOX');  Session.SaveConfigFile;  { Create the table. }   Table := TTable.Create(Self);  Table.DatabaseName := `MyDatabase';  Table.TableName := `MyTable.db';end;</PRE><P>This code first creates a BDE alias for a database called MyDatabase in the C:directory. After that, a TTable object is created, and the DatabaseName propertyis set to the alias created in the first part of the code. Finally, the TableNameproperty is set to the name of the new table you are going to create. At this pointthe TTable object has been created, but the table itself doesn't exist on disk.</P><P><H3><A NAME="Heading4"></A>Creating the Field Definitions</H3><P>The next step is to create the field definitions for the table's fields. As youmight guess, the field definitions describe each field. A field definition containsthe field name, its type, its size (if applicable), and whether the field is a requiredfield. The field's type can be one of the TFieldType values. Table 18.1 lists theTFieldType values.</P><P><H4>TABLE 18.1. DATABASE TABLE FIELD TYPES.</H4><P><TABLE BORDER="1">	<TR ALIGN="LEFT" VALIGN="TOP">		<TD ALIGN="LEFT"><I>Field type</I></TD>		<TD ALIGN="LEFT"><I>Description</I></TD>	</TR>	<TR ALIGN="LEFT" VALIGN="TOP">		<TD ALIGN="LEFT">ftUnkown</TD>		<TD ALIGN="LEFT">Unknown or undetermined</TD>	</TR>	<TR ALIGN="LEFT" VALIGN="TOP">		<TD ALIGN="LEFT">ftString</TD>		<TD ALIGN="LEFT">Character or string field</TD>	</TR>	<TR ALIGN="LEFT" VALIGN="TOP">		<TD ALIGN="LEFT">ftSmallint</TD>		<TD ALIGN="LEFT">16-bit integer field</TD>	</TR>	<TR ALIGN="LEFT" VALIGN="TOP">		<TD ALIGN="LEFT">ftInteger</TD>		<TD ALIGN="LEFT">32-bit integer field</TD>	</TR>	<TR ALIGN="LEFT" VALIGN="TOP">		<TD ALIGN="LEFT">ftWord</TD>		<TD ALIGN="LEFT">16-bit unsigned integer field</TD>	</TR>	<TR ALIGN="LEFT" VALIGN="TOP">		<TD ALIGN="LEFT">ftBoolean</TD>		<TD ALIGN="LEFT">Boolean field</TD>	</TR>	<TR ALIGN="LEFT" VALIGN="TOP">		<TD ALIGN="LEFT">ftFloat</TD>		<TD ALIGN="LEFT">Floating-point numeric field</TD>	</TR>	<TR ALIGN="LEFT" VALIGN="TOP">		<TD ALIGN="LEFT">ftCurrency</TD>		<TD ALIGN="LEFT">Money field</TD>	</TR>	<TR ALIGN="LEFT" VALIGN="TOP">		<TD ALIGN="LEFT">ftBCD</TD>		<TD ALIGN="LEFT">Binary-Coded Decimal field</TD>	</TR>	<TR ALIGN="LEFT" VALIGN="TOP">		<TD ALIGN="LEFT">ftDate</TD>		<TD ALIGN="LEFT">Date field</TD>	</TR>	<TR ALIGN="LEFT" VALIGN="TOP">		<TD ALIGN="LEFT">ftTime</TD>		<TD ALIGN="LEFT">Time field</TD>	</TR>	<TR ALIGN="LEFT" VALIGN="TOP">		<TD ALIGN="LEFT">ftDateTime</TD>		<TD ALIGN="LEFT">Date and time field</TD>	</TR>	<TR ALIGN="LEFT" VALIGN="TOP">		<TD ALIGN="LEFT">ftBytes</TD>		<TD ALIGN="LEFT">Fixed number of bytes (binary storage)</TD>	</TR>	<TR ALIGN="LEFT" VALIGN="TOP">		<TD ALIGN="LEFT">ftVarBytes</TD>		<TD ALIGN="LEFT">Variable number of bytes (binary storage)</TD>	</TR>	<TR ALIGN="LEFT" VALIGN="TOP">		<TD ALIGN="LEFT">ftAutoInc</TD>		<TD ALIGN="LEFT">Auto-incrementing 32-bit integer counter field</TD>	</TR>	<TR ALIGN="LEFT" VALIGN="TOP">		<TD ALIGN="LEFT">ftBlob</TD>		<TD ALIGN="LEFT">Binary large object field</TD>	</TR>	<TR ALIGN="LEFT" VALIGN="TOP">		<TD ALIGN="LEFT">ftMemo</TD>		<TD ALIGN="LEFT">Text memo field</TD>	</TR>	<TR ALIGN="LEFT" VALIGN="TOP">		<TD ALIGN="LEFT">ftGraphic</TD>		<TD ALIGN="LEFT">Bitmap field</TD>	</TR>	<TR ALIGN="LEFT" VALIGN="TOP">		<TD ALIGN="LEFT">ftFmtMemo</TD>		<TD ALIGN="LEFT">Formatted text memo field</TD>	</TR>	<TR ALIGN="LEFT" VALIGN="TOP">		<TD ALIGN="LEFT">ftParadoxOle</TD>		<TD ALIGN="LEFT">Paradox OLE field</TD>	</TR>	<TR ALIGN="LEFT" VALIGN="TOP">		<TD ALIGN="LEFT">ftDBaseOle</TD>		<TD ALIGN="LEFT">dBASE OLE field</TD>	</TR></TABLE></P><P><B>ftTypedBinary Typed binary field</B></P><P>You create a field definition by using the Add method of the TFieldDefs class.The FieldDefs property of TTable is a TFieldDefs object. Putting all this together,then, adding a new string field to a database would look like this:</P><P><PRE>Table.FieldDefs.Add(`Customer', ftString, 30, False);</PRE><P>This code line adds a string field called Customer with a size of 30 characters.The field is not a required field because the last parameter of the Add method isFalse. Add as many field definitions as you need, setting the appropriate data typeand size for each field.</P><P><H4>Creating the Index Definitions</H4><P>If your table will be indexed, you also need to add one or more index definitions.Adding index definitions is much the same as adding field definitions. The IndexDefsproperty of TTable contains the index definitions. To add a new index definition,call the Add method of TIndexDefs:</P><P><PRE>Table.IndexDefs.Add(`', `CustNo', [ixPrimary]);</PRE><P>The first parameter of the Add method is used to specify the index name. If youare creating a primary index (as in this example), you don't need to specify an indexname. The second field is used to specify the field or fields on which to index.If you have more than one field in the index, you separate each field with a semicolon--forexample,</P><P><PRE>Table.IndexDefs.Add(`', `Room;Time', [ixPrimary]);</PRE><P>The last parameter of the Add method is used to specify the index type. This parametertakes a TIndexOptions set. Different index options can be specified in combination.For example, an index might be a primary index that is sorted in descending order.In that case, the call to Add might look like this: <PRE></PRE><PRE>Table.IndexDefs.Add(`', `CustNo', [ixPrimary, ixDescending]);</PRE><H4>Creating the Table</H4><P>After you add all the field and index definitions to the table, you create thetable. So far you have been setting up the table's layout but haven't actually createdthe table. Creating the table is the easiest step of all:</P><P><PRE>Table.CreateTable;</PRE><P>The CreateTable method performs the actual creation of the table on disk. CreateTabletakes the contents of the FieldDefs and IndexDefs properties and creates the tablestructure, based on those contents.</P><P>Now that the table is created, you can fill it with data by using any method requiredfor your application. You can fill the table programmatically or allow your usersto add or edit the data from a form.</P><P>The book's code contains a program called MakeTabl. This program first createsa table and then fills it with data. The program fills the table with data from theCUSTOMER.TXT file created with the MakeText program earlier in the chapter. Listing18.2 contains the unit for the main form (MakeTblU.pas). Note that the uses listfor this program includes the DBGrids, DBTables, and DB units.</P><P><H4>LISTING 18.2. MakeTblU.pas.</H4><PRE>unit MakeTblU;interfaceuses  Windows, Messages, SysUtils, Classes, Graphics, Controls,  Forms, Dialogs, StdCtrls, Grids, DBGrids, DbTables, Db;type  TForm2 = class(TForm)    DBGrid: TDBGrid;</PRE><PRE>    CreateBtn: TButton;</PRE><PRE>    FillBtn: TButton;    procedure CreateBtnClick(Sender: TObject);    procedure FillBtnClick(Sender: TObject);  private    { Private declarations }   public    { Public declarations }   end;<I></I>var  Form2: TForm2;implementation{$R *.DFM} procedure TForm2.CreateBtnClick(Sender: TObject);const  Dir : PChar = `c:';var  Table : TTable;begin{ Create a BDE alias, but only if it doesn't already exist. }   if not Session.IsAlias(`MyDatabase') then begin    CreateDirectory(Dir, nil);    try      Session.AddStandardAlias(`MyDatabase', Dir, `PARADOX');      Session.SaveConfigFile;    except      MessageDlg(`Error Creating Alias', mtError, [mbOk], 0);      Exit;    end;  end;  { Now create the Table. }   Screen.Cursor := crHourGlass;  Table := TTable.Create(Self);  try    Table.DatabaseName := `MyDatabase';    Table.TableName := `MyTable.db';    { Add the field definitions for each field. }     Table.FieldDefs.Add(`CustNo', ftFloat, 0, True);    Table.FieldDefs.Add(`Customer', ftString, 30, False);    Table.FieldDefs.Add(`Addr1', ftString, 30, False);    Table.FieldDefs.Add(`Addr2', ftString, 30, False);</PRE><PRE>    Table.FieldDefs.Add(`City', ftString, 15, False);</PRE><PRE>    Table.FieldDefs.Add(`State', ftString, 20, False);    Table.FieldDefs.Add(`Zip', ftString, 10, False);    Table.FieldDefs.Add(`Phone', ftString, 15, False);    Table.FieldDefs.Add(`Fax', ftString, 15, False);    { Add an index definition for the primary key. }     Table.IndexDefs.Add(`', `CustNo', [ixPrimary]);    { Everything is set up, so create the Table. }     Table.CreateTable;  except    MessageDlg(`Error Creating Table', mtError, [mbOk], 0);    Screen.Cursor := crDefault;    Table.Free;    Exit;  end;  { All done, so let the user know. }   Table.Free;  Screen.Cursor := crDefault;  CreateBtn.Enabled := False;  FillBtn.Enabled := True;  MessageDlg(    `Table Created Successfully', mtInformation, [mbOk], 0);end;procedure TForm2.FillBtnClick(Sender: TObject);var  Table      : TTable;  Datasource : TDataSource;  Lines      : TStringList;  S, S2      : string;  I, P       : Integer;begin  { Create a TTable. }   Table := TTable.Create(Self);  Table.DatabaseName := `MyDatabase';  Table.TableName := `MyTable.db';  { Create a data source and hook it up to the Table. }   { Then hook the DBGrid to the datasource. }   Datasource := TDataSource.Create(Self);  Datasource.DataSet := Table;  DBGrid.Datasource := Datasource;  { Open the Table and the text file. }   Table.Active := True;  Lines := TStringList.Create;  Lines.LoadFromFile(`customer.txt');  { Put the Table in edit mode. }   Table.Edit;  { Process the Lines. }   for I := 0 to Pred(Lines.Count) do begin    { Append a record to the end of the file. }     Table.Append;    { Parse the string and get the first value. }     S := Lines[I];    P := Pos(`,', S);    S2 := Copy(S, 1, P - 1);    Delete(S, 1, P);    { Write the value to the CustNo field. }     Table.FieldByName(`CustNo').Value := StrToInt(S2);    { Continue for each of the fields. }     P := Pos(`,', S);    S2 := Copy(S, 1, P - 1);    Delete(S, 1, P);    Table.FieldByName(`Customer').Value := S2;    P := Pos(`,', S);    S2 := Copy(S, 1, P - 1);    Delete(S, 1, P);    Table.FieldByName(`Addr1').Value := S2;    P := Pos(`,', S);    S2 := Copy(S, 1, P - 1);    Delete(S, 1, P);    Table.FieldByName(`Addr2').Value := S2;    P := Pos(`,', S);    S2 := Copy(S, 1, P - 1);    Delete(S, 1, P);    Table.FieldByName(`City').Value := S2;    P := Pos(`,', S);    S2 := Copy(S, 1, P - 1);    Delete(S, 1, P);    Table.FieldByName(`State').Value := S2;    P := Pos(`,', S);    S2 := Copy(S, 1, P - 1);    Delete(S, 1, P);    Table.FieldByName(`Zip').Value := S2;    P := Pos(`,', S);    S2 := Copy(S, 1, P - 1);    Delete(S, 1, P);    Table.FieldByName(`Phone').Value := S2;    P := Pos(`,', S);    S2 := Copy(S, 1, P - 1);

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -