用Delphi动态建立ODBC数据源

软件世界

在数据库编程中经常会遇到用ODBC(开放式数据库连接)连接数据源问题,用ODBC连接数据源也是最方便最实用的方法。我们有时会动态创建一个数据库,如果能动态建立ODBC数据源并进行连接就非常方便。下面就介绍如何用Delphi在程序中动态建立ODBC数据源(以连接MS-Access数据库为例)。

一、步骤

1.打开Delphi,建立一个新的应用程序:Project1。
2.依次添加ToolBar1、ADOConnection1、ADOTable1、DataSource1、DBGrid1、OpenDialog1各一个。
3.在ToolBar1添加ToolButton1、ComboBox1各一个。
4.设置:
ADOTable1.Connection:=ADOConnection1;
DataSource1.Dataset = ADOTable1;
DBGrid1. DataSource = DataSource1;

二、完整的源代码

unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Registry, ExtCtrls, DBCtrls, ImgList, ComCtrls, ToolWin, Grids, DBGrids,
Db, ADODB, StdCtrls;
type
TForm1 = class(TForm)
ADOConnection1:TADOConnection;
ADOTable1: TADOTable;
DataSource1: TDataSource;
DBGrid1: TDBGrid;
OpenDialog1: TOpenDialog;
ToolBar1: TToolBar;
ToolButton1: TToolButton;
ImageList1: TImageList;
DBNavigator1: TDBNavigator;
ComboBox1: TComboBox;
procedure ToolButton1Click(Sender: TObject);
procedure ComboBox1Change(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
Function ReadODBCDriver(Name:String):String;
Function CreateMsAccess(Path:String;driver:String):Boolean;
implementation
{$R *.DFM}
Function ReadODBCDriver(Name:String):String; //读取驱动程序位置
var
registerTemp : TRegistry;
begin
registerTemp := TRegistry.Create;
//读取MS_ACCESS 驱动程序位置
If Name='Access' Then
begin
with registerTemp do
begin
RootKey:=HKEY_LOCAL_MACHINE;
if OpenKey('Software\ODBC\ODBCINST.INI\Microsoft Access Driver (*.mdb)',True) then
begin
ReadODBCDriver:=ReadString('Driver');
CloseKey;
Free;
Exit;
End;
End;
End;
registerTemp.Free;
ReadODBCDriver:='';
End;
Function CreateMsAccess(Path:String;driver:String):Boolean;
var
registerTemp : TRegistry;
bData : array[ 0..0 ] of byte;
begin
If Driver='' then Begin
Showmessage('读取ODBC驱动程序失败,请重新安装ODBC!'); Exit;End;
registerTemp := TRegistry.Create;
CreateMsAccess:=True;
//建立一个Registry实例
with registerTemp do
begin
RootKey:=HKEY_LOCAL_MACHINE;
//设置根键值为HKEY_LOCAL_MACHINE
//找到Software\ODBC\ODBC.INI\ODBC Data Sources
if OpenKey('Software\ODBC\ODBC.INI\ODBC Data Sources',True) then
begin //注册一个DSN名称
WriteString('TemAccess', 'Microsoft Access Driver (*.mdb)');
end
else
begin//创建键值失败
CreateMsAccess:=False;
exit;
end;
CloseKey;
//找到或创建Software\ODBC\ODBC.INI\TemAccessDataBase,写入DSN配置信息
if OpenKey('Software\ODBC\ODBC.INI\TemAccess',True) then
begin
WriteString('DBQ', Path);//数据库目录,连接你的数据库
WriteString('Description','LyhAccessDataBase');//数据源描述
WriteString('Driver',Driver);//驱动程序DLL文件
WriteInteger('DriverId',25);
//驱动程序标识
WriteString('FIL','Ms Access;');
//Filter依据
WriteInteger('SafeTransaction',0);
//支持的事务操作数目
WriteString('UID','');//用户名称
bData[0]:= 0;
WriteBinaryData('Exclusive',bData,1);
//非独占方式
WriteBinaryData('ReadOnly',bData,1);
//非只读方式
end
else//创建键值失败
begin
CreateMsAccess:=False;
exit;
end;
CloseKey;
//找到或创建Software\ODBC\ODBC.INI\TemAccessDataBase\Engines\Jet写入DSN数据库引擎配置信息
if OpenKey('Software\ODBC\ODBC.INI\TemAccess\Engines\Jet',True) then
begin
WriteString('ImplicitCommitSync','Yes');
WriteInteger('MaxBufferSize',512);//缓冲区大小
WriteInteger('PageTimeout',10);//页超时
WriteInteger('Threads',3);//支持的线程数目
WriteString('UserCommitSync','Yes');
end
else//创建键值失败
begin
CreateMsAccess:=False;
exit;
end;
CloseKey;
Free;
end;
end;
procedure TForm1.ToolButton1Click(Sender: TObject);
Var FileName:String;
begin
IF Opendialog1.Execute then
begin
ADOConnection1.Connected:=False;
FileName:=Opendialog1.FileName;
//创建 ODBC
CreateMsAccess(FileName,ReadODBCDriver('Access'));
//连接 ODBC
ADOConnection1.ConnectionString:='Provider=MSDASQL.1;Persist Security Info=False;Data Source=TemAccess;Mode=ReadWrite';
ADOConnection1.Connected:=True;
ADOConnection1.GetTableNames(ComboBox1.Items,False);
ComboBox1.ItemIndex:=0;
ADOTable1.Connection:=ADOConnection1;
ADOTable1.TableName:=ComboBox1.Text;
ADOTable1.open;
end;
end;
procedure TForm1.ComboBox1Change(Sender: TObject);
begin
ADOTable1.Active:=False;
ADOTable1.TableName:=ComboBox1.Text;
ADOTable1.open;
end;
end.
注:以上程序在Win98+Delphi 5.0及Win2000+Delphi 6.0调试通过。如果需要连接其他数据源,只需将程序稍作改动就可以了。有兴趣的朋友可以参考程序“数据浏览器”,该程序的下载地址:http://lqohero.51.net/lyh/program/gdd/brighteye.exe。