ado工厂
//==============================================================================
// ADO数据工厂 cxg 2008-09-26 14:37:23
//==============================================================================
unit uADOFactory;
interface
uses
SysUtils,ADODB,DB,Classes,ActiveX,IniFiles,Forms;
const
c_SqlSvrPrd='sqloledb';
c_AccessPrd='microsoft.jet.oledb.4.0';
{ 生成TADOConnection }
function GetADOConn(Owner:TComponent;AProvider:Integer=1):TADOConnection;
{ 生成TADOQuery }
function GetADODataSet(Owner:TComponent;AConn:TADOConnection;ASQL:string):TADOQuery;
{ 生成TDataSource对象 }
function GetDataSource(Owner:TComponent):TDataSource;
{ TDataSource绑定数据集 }
procedure LinkControl(ADataSet:TDataSet;ADataSource:TDataSource);
implementation
function GetDataSource(Owner:TComponent):TDataSource;
var
FDataSource:TDataSource;
begin
FDataSource:=TDataSource.Create(Owner);
Result:=FDataSource;
end;
procedure LinkControl(ADataSet:TDataSet;ADataSource:TDataSource);
begin
ADataSource.DataSet:=ADataSet;
end;
//==============================================================================
// AProvider=1 sql Server: 'sqloledb'
// AProvider=2 Access: 'Microsoft.Jet.OLEDB.4.0'
//==============================================================================
function GetADOConn(Owner:TComponent;AProvider:Integer=1):TADOConnection;
var
Conn:TADOConnection;
sFileName,sSection:string;
ini:TIniFile;
begin
sFileName:=ExtractFilePath(Application.ExeName)+'db.ini';
Conn:=TADOConnection.Create(Owner);
with Conn do
begin
LoginPrompt:=False;
ini:=TIniFile.Create(sFileName);
try
if AProvider=1 then
begin
Provider:=c_SqlSvrPrd;
sSection:='sql server';
Properties['Data Source'].Value:=ini.ReadString(sSection,'server','');
Properties['User ID'].Value:=ini.ReadString(sSection,'userid','');
Properties['Password'].Value:=ini.ReadString(sSection,'password','');
Properties['Initial Catalog'].Value:=
ini.ReadString(sSection,'database','');
end;
if aprovider=2 then
begin
Provider:=c_AccessPrd;
sSection:='access';
Properties['Jet OLEDB:Database Password'].Value:=
ini.ReadString(sSection,'database password','');
Properties['Data Source'].Value:=ini.ReadString(sSection,'server','');
Properties['User ID'].Value:=ini.ReadString(sSection,'userid','');
Properties['Password'].Value:=ini.ReadString(sSection,'password','');
end;
try
Connected:=True;
Result:=Conn;
except
Result:=nil;
raise Exception.Create('数据库连接失败');
end;
finally
ini.Free;
end;
end;
end;
function GetADODataSet(Owner:TComponent;AConn:TADOConnection;ASQL:string):TADOQuery;
var
DataSet:TADOQuery;
begin
dataset:=TADOQuery.Create(owner);
dataset.Connection:=aconn;
with dataset do
begin
Close;
SQL.Clear;
SQL.Text:=ASQL;
Open;
end;
Result:=DataSet;
end;
end.
本文来自博客园,作者:{咏南中间件},转载请注明原文链接:https://www.cnblogs.com/hnxxcxg/archive/2008/09/26/2940815.html