Delphi中用ADO控件连接数据库例子

Delphi中用ADO控件连接数据库例子

来源:dudongxiao的专栏 作者:dudongxiao 时间:2008-05-04 点击:777 次
一、说明

最近在写个“数据库管理系统框架程序”,其中封装了几个连接数据库的函数,觉得挺好用,拿出来与大家分享下,希望能对大家有点用处。

我以连接oracle和access为例,其余数据库连接在此基础上稍加修改,便可使用。

二、连接oracle

1、源码
{
功能:连接ORACLE数据库
参数:sServerName ORACLE服务名,sUserName 用户名,sUserPwd 密码
}
function LinkOracle(sServerName, sUserName, sUserPwd: string): boolean;
begin
Result := True;
if _adoConn <> nil then _adoConn.Free;
_adoConn := TADOConnection.Create(nil);
_adoConn.ConnectionString := 'Provider=MSDAORA.1;'+
'Password='+sUserPwd+';'+
'User ID='+sUserName+';'+
'Data Source='+sServerName+';'+
'Persist Security Info=True';
_adoConn.LoginPrompt := False;

try
_adoConn.Open;
except
on E: Exception do
begin
Application.MessageBox(PChar('连接ORACLE失败!原因:' + E.message), '系统错误', MB_OK+MB_ICONERROR);
Result := False;
end;
end;
end;

{
功能:返回成功连接上数据库的ADOConnection实例
}
function GetAdoConnection: TADOConnection;
begin
Result := _adoConn;
if _adoConn = nil then
begin
Application.MessageBox('尚未创建数据库连接!', '系统错误', MB_OK+MB_ICONERROR);
Exit;
end;
try
if not _adoConn.Connected then
_adoConn.Connected := True;
except
on E: Exception do
Application.MessageBox(PChar('Exception in GetAdoConnection: '+E.Message), '系统错误', MB_OK+MB_ICONERROR);
end;
end;

上面是我封装的连接oracle的函数,下面对代码进行简单介绍:

_adoConn 是 TADOConnection 变量,被申明成在单元内可见的变量,这样方便在LinkOracle和GetAdoConnection中共同使用,又不至于对其他单元文件产生影响。

2、应用举例

例子:假设数据库服务名是orcl,用户名是scott,密码是tiger,连接该用户,并查出该用户有几张表。

begin
if not LinkOracle('orcl', 'scott', 'tiger') then
begin
showmessage('连接数据库失败');
Exit;
end;

with TADOQuery.Create(nil) do
try
Connection := GetAdoConnection;
sql.add(' select count(*) cnt from tab ');
open;
showmessage('共有' + fieldbyname('cnt').AsString + '张');
finally
close;
free;
end;
end;

三、连接access

1、源码
{
功能:创建AccessODBC数据源
参数:sDsn为数据源的名称, sMdbPath为数据库的名称包括目录, sUserId为用户名, sUserPwd为密码
}
function CreateAccessODBCDataSource(sDsn, sMdbPath, sUserId, sUserPwd: string): boolean;
var
Reg: TRegistry;
bData : array[ 0..0 ] of byte;
begin
Reg :=TRegistry.Create;
with Reg do
begin
RootKey:=HKEY_LOCAL_MACHINE;
if OpenKey('Software\ODBC\ODBC.INI\ODBC Data Sources',true) then
begin
WriteString(sDsn,'Microsoft Access Driver (*.mdb)');
end
else
begin
Result:=False;
Application.MessageBox('创建ODBC数据源失败', '系统错误', MB_OK+MB_ICONERROR);
Exit;
end;
CloseKey;

if OpenKey('Software\ODBC\ODBC.INI\'+sDsn,true) then
begin
WriteString('DBQ', sMdbPath);//数据库目录
WriteString('Description',sMdbPath+'数据源');
WriteString('Driver','C:\Windows\System32\odbcjt32.dll');
WriteInteger('DriverId', 25 );
WriteString('FIL', 'Ms Access;'); //Filter依据
WriteInteger('SafeTransaction', 0 ); //支持的事务操作数目
WriteString('UID', sUserId); //用户名称
WriteString('PWD', sUserPwd); //用户密码
bData[0] := 0;
WriteBinaryData('Exclusive', bData, 1 );//非独占方式
WriteBinaryData('ReadOnly', bData, 1 );//非只读方式
end
else
begin
Result:=False;
Application.MessageBox('创建ODBC数据源失败', '系统错误', MB_OK+MB_ICONERROR);
Exit;
end;
CloseKey;

if OpenKey('Software\ODBC\ODBC.INI\'+sDsn+'\Engines\Jet',true) then
begin
WriteString('ImplicitCommitSync','Yes');
WriteInteger('MaxBufferSize',2048 );//缓冲区大小
WriteInteger('PageTimeout',5 );//页超时
WriteInteger('Threads',3 );//支持的线程数目
WriteString('UserCommitSync','Yes');
end
else
begin
Result:=False;
Application.MessageBox('创建ODBC数据源失败', '系统错误', MB_OK+MB_ICONERROR);
Exit;
end;
CloseKey;
Result:=True;
Free;
end;
end;

{
功能:连接ACCESS
参数:sDsn为数据源的名称
}
function LinkAccess(sDsn: string): Boolean;
begin
Result := True;
if _adoConn <> nil then _adoConn.Free;
_adoConn := TADOConnection.Create(Application);
_adoConn.ConnectionString := 'Provider=MSDASQL.1;Persist Security Info=False;Data Source=' + sDsn;
_adoConn.LoginPrompt := False;

_adoConn.Open;
if not _adoConn.Connected then
begin
Application.MessageBox('连接ACCESS失败!', '系统错误', MB_OK+MB_ICONERROR);
Result := False;
end;
end;

{
功能:返回成功连接上数据库的ADOConnection实例
}
function GetAdoConnection: TADOConnection;
begin
Result := _adoConn;
if _adoConn = nil then
begin
Application.MessageBox('尚未创建数据库连接!', '系统错误', MB_OK+MB_ICONERROR);
Exit;
end;
try
if not _adoConn.Connected then
_adoConn.Connected := True;
except
on E: Exception do
Application.MessageBox(PChar('Exception in GetAdoConnection: '+E.Message), '系统错误', MB_OK+MB_ICONERROR);
end;
end;

上面是我封装的连接access的函数,下面对代码进行简单介绍:
_adoConn 是 TADOConnection 变量,被申明成在单元内可见的变量,这样方便在LinkAccess和GetAdoConnection中共同使用,又不至于对其他单元文件产生影响。
2、应用举例
举例:我在e盘下有个access文件,名为db1.mdb, 该文件设了密码也为db1。下面代码为连接该文件的例子

begin
if CreateAccessODBCDataSource('accessDataSource', 'e:\db1.mdb', 'db1', 'db1') then
begin
if LinkAccess('accessDataSource') then
begin
with TADOQuery.Create(nil) do
try
Connection := GetAdoConnection;
SQL.Clear;
SQL.Add('自己写吧');
Open;
finally
close;
Free;
end;
end;
end;
end;
posted @ 2009-02-25 16:29  苔苔以苔苔以苔  阅读(2136)  评论(0编辑  收藏  举报
猪先飞