将DELPHI数据库连接写进INI配置文件中

procedure TDM.DataModuleCreate(Sender: TObject);

var piececonfg:Tinifile;

pathconfgstr,Providerstr,UserIDstr,

Passwordstr,DataSourceStr,DatabaseNamestr :string;

begin

pathconfgstr:= ExtractFilePath(Application.ExeName);

if pathconfgstr[length(pathconfgstr)]='/' then

begin

pathconfgstr:=pathconfgstr+'piececonfg.ini';

piececonfg:=Tinifile.Create(pathconfgstr);

end

else

begin

pathconfgstr:=pathconfgstr+'/piececonfg.ini';

piececonfg:=Tinifile.Create(pathconfgstr);

end;

if not FileExists(pathconfgstr) then

begin

application.MessageBox('配置文件不存在!','提示',mb_ok);

application.Terminate;

end;

Providerstr:=piececonfg.ReadString('DataBaseConfig','Provider','');

UserIDstr:=piececonfg.ReadString('DataBaseConfig','UserID','');

Passwordstr:=piececonfg.ReadString('DataBaseConfig','Password','');

DataSourceStr:=piececonfg.ReadString('DataBaseConfig','DataSource','');

DatabaseNamestr:=piececonfg.ReadString('DataBaseConfig','DatabaseName','');

if (Providerstr='') or (DataSourceStr='') or (DatabaseNamestr='') then

begin

application.MessageBox('数据库配置不正确,请重新配置!','提示',mb_ok);

Application.Terminate;

end;

adoconn.Close;

adoconn.ConnectionString:='';

adoconn.ConnectionString:='Provider='+Providerstr+';User;

Password='+Passwordstr+';Data Source='+DataSourceStr+

Initial Catalog='+DatabaseNamestr;

try

adoconn.Connected:=true;

except

application.MessageBox('数据库配置不正确,请重新配置!','提示',mb_ok);

adoconn.Connected:=false;

application.Terminate;

end;

search:=TstringList.create;

end;

piececonfg.ini

++++++++++++++++++++++++++++++++++++++++++++

[DataBaseConfig]

Provider=SQLOLEDB.1

UserID=sa

Password=sa

DataSource=192.168.1.1

DatabaseName=mjj

======================================================

8、 释放:inifile.distory;或inifile.free;

INI文件操作

(1) INI文件的结构:

;这是关于INI文件的注释部分

[节点]

关键字=值

...

INI文件允许有多个节点,每个节点又允许有多个关键字, “=”后面是该关键字的值(类型有三种:字符串、整型数值和布尔值。其中字符串存贮在INI文件中时没有引号,布尔真值用1表示,布尔假值用0表示)。注释以分号“;”开头。

(2) INI文件的操作

1、 在Interface的Uses节增加IniFiles;

2、 在Var变量定义部分增加一行:inifile:Tinifile;然后,就可以对变量myinifile进行创建、打开、读取、写入等操作了。

3、 打开INI文件:inifile:=Tinifile.create('tmp.ini');

4、 读取关键字的值:

a:=inifile.Readstring('节点','关键字',缺省值);// string类型

b:=inifile.Readinteger('节点','关键字',缺省值);// integer类型

c:=inifile.Readbool('节点','关键字',缺省值);// boolean类型

其中[缺省值]为该INI文件不存在该关键字时返回的缺省值。

5、 写入INI文件:

inifile.writestring('节点','关键字',变量或字符串值);

inifile.writeinteger('节点','关键字',变量或整型值);

inifile.writebool('节点','关键字',变量或True或False);

当这个INI文件的节点不存在时,上面的语句还会自动创建该INI文件。

6、 删除关键字:

inifile.DeleteKey('节点','关键字');//关键字删除

inifile.EraseSection('节点');// 节点删除

7、 节点操作:

inifile.readsection('节点',TStrings变量);//可将指定小节中的所有关键字名读取至一个字符串列表变量中;

inifile.readsections(TStrings变量);//可将INI文件中所有小节名读取至一个字符串列表变量中去。

inifile.readsectionvalues('节点',TStrings变量);//可将INI文件中指定小节的所有行(包括关键字、=、值)读取至一个字符串列表变量中去。

8、 释放:inifile.distory;或inifile.free;