日期:2014-05-16  浏览次数:20525 次

Delphi连接数据库通用方法

DELPHI 连接数据库是个头痛的问题,现在我写了个通用方法,由一个配置工具和一个配置文件实现数据库连接并且可以加密字符串,有需要的留下邮箱,发给你。

?

1.新建一个窗体,放置5个控件,(TADOConnection的ConnectionString属性不需要指定连接字段)如下:
??? dbgrd1: TDBGrid;
??? ADOConnection: TADOConnection;
??? ds1: TDataSource;
??? qry1: TADOQuery;

??? Button1: TButton;

?

2.主要几个事件的定义以及编写

?function GetSysPath:String;? //获取系统运行路径
? function ReadConnectionStr: String; //读取配制工具连接字符串
? function Decode(S:string):string;? //解码
? function Encode(S:string):string;? //编码

?

//获取系统运行路径
function GetSysPath:String;?
begin
? Result:=ExtractFilePath(ParamStr(0));
end;


//程序创建
procedure TForm1.FormCreate(Sender: TObject);
begin
?ADOConnection.ConnectionString:=ReadConnectionStr;
? try
??? ADOConnection.Connected:=True;
? except
??? on e:Exception do
????? begin
??????? ADOConnection.Connected:=False;
??????? ShowMessage('数据库链接失败!请通过DbSetup.exe进行数据库配置,文件为(DBConfig.Ini)'+#13+e.Message);
????? end;
? end;
end;

//编码
function Encode(S:string):string;
var
??? Pwd,Bt:Byte;
??? I:Integer;
begin
??? if s = '' then
??? begin
??????? Result:='';
??????? Exit;
??? end;
??? Pwd := Trunc((Now()-Date())*24*3600) mod 256;
??? Result:=Chr(Pwd);
??? for I:=1 to Length(S) do
??? begin
??????? Bt:=(Byte(S[I]) xor Pwd);
??????? Result:=Result + Chr(Bt);
??? end;
end;

//解码
function Decode(S:string):string;
var
??? Pwd,Bt:Byte;
??? I:Integer;
begin
??? if S = '' then
??? begin
??????? Result:='';
??????? Exit;
??? end;
??? Pwd := Byte(S[1]);
??? for I:=2 to Length(S) do
??? begin
??????? Bt:=((Byte(S[I])) xor Pwd);
??????? Result:=Result+ Chr(Bt);
??? end;
end;

//读取配制工具连接字符串
function ReadConnectionStr: String;
var
??? DBConfig:file;
??? FileLen:Integer;
??? Buff:array[1..1024] of Char;
??? I:Integer;
begin
? if not FileExists(Trim(GetSysPath)+'DBConfig.Ini') then
??? begin
????? Result:='';
????? Exit;
??? end;
? try
??? AssignFile(DBConfig,Trim(GetSysPath)+'DBConfig.Ini');
??? Reset(DBConfig,1);
??? try
??????? FileLen:=FileSize(DBConfig);
??????? BlockRead(DBConfig,Buff,FileLen);
??? finally
??????? CloseFile(DBConfig);
??? end;
??? for I:=1 to FileLen do
??????? Result :=Result+Buff[I];
??? Result := Decode(Result);
? except
??? Result:='';
? end;
end;

//Button1按钮测试数据获取是否正常
procedure TForm1.Button1Click(Sender: TObject);
begin
? qry1.Close;
? qry1.SQL.Add('select * from tabel1');
? qry1.Open;
end;


以上实例在Delphi 7 + SQL 2000 下测试通过,唯一的特点就是连接数据库的字符串加密了。

?