我一般是用了一个INI文件来配置数据库连接信息,虽然比较老土,但是很实用哦function GetConnectionString: string;
var
SYSINI: TINIFile;
ServerName, UserName, Password, InitDB: string;
tmpstr: string;
begin
SYSINI := TIniFile.Create('DB.INI');
try
ServerName := SYSINI.ReadString('Database', 'ServerName', '');
UserName := SYSINI.ReadString('Database', 'UserName', '');
InitDB := SYSINI.ReadString('Database', 'InitDB', '');
tmpstr := SYSINI.ReadString('Database', 'Password', '');
Password := Decrypt(tmpstr, Key);
Result := '';
Result := 'Provider=SQLOLEDB.1;Password=' + Password + ';Persist Security Info=True;User ID=' + UserName + ';Initial Catalog=' + InitDB + ';Data Source=' + ServerName;
finally
SYSINI.Free;
end;
end;procedure SetConnectionString(ServerName, UserName, Password, InitDB: string);
var
SYSINI: TINIFile;
tmpstr: string;
begin
SYSINI := TIniFile.Create('DB.INI');
try
with SYSINI do
begin
WriteString('Database', 'ServerName', ServerName);
WriteString('Database', 'UserName', UserName);
WriteString('Database', 'InitDB', InitDB);
tmpstr := Encrypt(Password, Key);
WriteString('Database', 'Password', tmpstr);
end;
finally
SYSINI.Free;
end;
end;
这里我动态生成了访问SQL Server的ADOConnection.ConnectionString字符串,中间为了保存口令,我用了一个加密和解密函数,就是普通的,你随便用一个对称加密函数就可以
var
SYSINI: TINIFile;
ServerName, UserName, Password, InitDB: string;
tmpstr: string;
begin
SYSINI := TIniFile.Create('DB.INI');
try
ServerName := SYSINI.ReadString('Database', 'ServerName', '');
UserName := SYSINI.ReadString('Database', 'UserName', '');
InitDB := SYSINI.ReadString('Database', 'InitDB', '');
tmpstr := SYSINI.ReadString('Database', 'Password', '');
Password := Decrypt(tmpstr, Key);
Result := '';
Result := 'Provider=SQLOLEDB.1;Password=' + Password + ';Persist Security Info=True;User ID=' + UserName + ';Initial Catalog=' + InitDB + ';Data Source=' + ServerName;
finally
SYSINI.Free;
end;
end;procedure SetConnectionString(ServerName, UserName, Password, InitDB: string);
var
SYSINI: TINIFile;
tmpstr: string;
begin
SYSINI := TIniFile.Create('DB.INI');
try
with SYSINI do
begin
WriteString('Database', 'ServerName', ServerName);
WriteString('Database', 'UserName', UserName);
WriteString('Database', 'InitDB', InitDB);
tmpstr := Encrypt(Password, Key);
WriteString('Database', 'Password', tmpstr);
end;
finally
SYSINI.Free;
end;
end;
这里我动态生成了访问SQL Server的ADOConnection.ConnectionString字符串,中间为了保存口令,我用了一个加密和解密函数,就是普通的,你随便用一个对称加密函数就可以
例如安装到同一目录下,或EXE文件目录的某个子目录。
然后在代码中得到EXE文件的路径即可算出数据库的具体位置,
例如ExtractFilePath(Paramstr(0))可以得到执行文件的路径,
再在ConnectionString中指定数据库的位置。
extractfilepath(ParamStr(0))返回安装目录的路径了。procedure TForm1.FormCreate(Sender: TObject);
begin
ADOConnection1.ConnectionString :='Provider=Microsoft.Jet.OLEDB.4.0;Data Source='
+ extractfilepath(ParamStr(0))+'\dbdemos.mdb;Persist Security Info=False';
ADOConnection1.Connected :=true;
end;