下面以一个实例来说明:在 ‘c:\’ 下有一个数据库‘Renshi.dbf’,字段为:‘bianhao’;‘xingming’,类型为字符型,以关键字段‘bianhao’为索引字段,建立数据库的连接。
我们用控件DBNavigator1、DataSource1、Table1、DBedit1、 DBedit2、Table2来建立数据库的连接。其各属性为: Table1.databasename:='c:\'; Table1.tablename:='renshi.dbf'; Table1.active:=true; DataSource1.dataset:=table1; DBNavigator1.datasource:=DataSource1;
编号:对应字段bianhaio; 姓名:对应xingming字段; dbedit1.datasource:=DataSource1; dbedit1.datafield:='bianhao'; dbedit2.datasource:=DataSource1; dbedit2.datafield:='xingming';
这样数据库的连接就建立好了。
这里我们要求‘编号’为关键字段,不允许重复输入,为了控制输入的编号为唯一,我们在数据库变化时对Table1加入一个Beforepost事件,程序如下: procedure TForm1.Table1BeforePost(DataSet: TDataSet); begin with table2 do begin databasename:='c:\'; tablename:='renshi.dbf'; indexfieldnames:='bianhao'; if not active then open; {判断数据库是否打开} Refresh; {刷新数据库} setkey; {设置数据库为搜索状态} fieldbyname('bianhao').asstring:=dbedit1.text; {设置输入的编号 字段内容为搜索的标准} gotokey; {移动到搜寻的记录上,完成搜索} if gotokey then {如果找到搜索的记录,则gotokey返回true} begin showmessage('输入的编号已存在!请重新输入'); abort; {终止该操作} end; end; end;
这样,就保证了‘编号’字段的唯一性,当重复输入时,计算机就会提示出错信息,并且该数据不能保存,只能进行修改或放弃保存操作。 该程序在Delphi4.0下调试通过。
|