不通过
WINDOWS
直接通过程序建立数据源详解
(vb
访问注册表
)
通过程序建立
WINDOWS
数据源
,
在
VB
中可以通过
API
函数实现
,
这不是这篇文章所要讨论的
,
这里主要是利用
WshShell
对象让
VB
便捷的操作注册表以达到建立
WINDOWS
数据源的目的
,
读完本文,你绝不仅仅是学会如何通过程序建立数据源。
(一)利用
WshShell
操作注册表理论基础
这可以参照我
BLOG
中转载的《
WshShell
对象详解
》,这篇文章把如何操作注册表部分说得很详细,值得仔细阅读。
(三)通过程序建立数据源案例子参考
案例需求:现在要在一个数据库管理软件安装后,第一次登陆时就自动完成数据源(DSN)的建立,而无需客户手动在windows系统中再建数据源。需要建立的数据源如下
1) 利用程序自动创建用于连接SQL Server的ODBC,需连接局域网中的名为:rcscpc 的SQL服务器,连接采用SQL Server验证,UID=sa,PWD=sa,连接默认数据库名:rcsc
2) 利用程序自动创建用于连接ACCESS 的ODBC, 要连接的ACCESS数据库在远程机器上
具体操作:
1) 首先VB需要引用wshom.ocx,否则编译器不会识别WshShell对象,引用方法,在VB中选择”工程”下的”引用”将”Windows Script Host Object Model”前面的钩钩上就可以了。
2) 在模块或者通用声明中声明WshShell对象,代码如下:
Option Explicit
Dim a As New WshShell
3) 操作注册表的主体代码:
Private Sub Form_Load()
'自动写入 rsdl-Odbc
Dim bm As Variant
a.RegWrite "HKLM/SOFTWARE/ODBC/ODBC.INI/feiyong/", ""
a.RegWrite "HKLM/SOFTWARE/ODBC/ODBC.INI/rsdl/Database", "rcsc"
a.RegWrite "HKLM/SOFTWARE/ODBC/ODBC.INI/rsdl/Driver", "C:/WINDOWS/system32/sqlsrv32.dll"
a.RegWrite "HKLM/SOFTWARE/ODBC/ODBC.INI/rsdl/LastUser", "sa"
a.RegWrite "HKLM/SOFTWARE/ODBC/ODBC.INI/rsdl/Server", "rcscpc"
a.RegWrite "HKLM/SOFTWARE/ODBC/ODBC.INI/ODBC Data Sources/rsdl", "SQL Server"
'自动写入 feiyong-odbc
a.RegWrite "HKLM/SOFTWARE/ODBC/ODBC.INI/feiyong/", ""
a.RegWrite "HKLM/SOFTWARE/ODBC/ODBC.INI/feiyong/DBQ", "//196.114.113.128/db/zongku.mdb"
a.RegWrite "HKLM/SOFTWARE/ODBC/ODBC.INI/feiyong/Driver", "C:/WINDOWS/system32/odbcjt32.dll"
a.RegWrite "HKLM/SOFTWARE/ODBC/ODBC.INI/feiyong/DriverId", &H19, "REG_DWORD"
a.RegWrite "HKLM/SOFTWARE/ODBC/ODBC.INI/feiyong/Exclusive", &O0, "REG_BINARY"
a.RegWrite "HKLM/SOFTWARE/ODBC/ODBC.INI/feiyong/FIL", "MS Access;"
a.RegWrite "HKLM/SOFTWARE/ODBC/ODBC.INI/feiyong/ReadOnly", &O1, "REG_BINARY"
a.RegWrite "HKLM/SOFTWARE/ODBC/ODBC.INI/feiyong/SafeTransactions", &H0, "REG_DWORD"
a.RegWrite "HKLM/SOFTWARE/ODBC/ODBC.INI/feiyong/UID", ""
a.RegWrite "HKLM/SOFTWARE/ODBC/ODBC.INI/feiyong/Engines/", ""
a.RegWrite "HKLM/SOFTWARE/ODBC/ODBC.INI/feiyong/Engines/Jet/", ""
a.RegWrite "HKLM/SOFTWARE/ODBC/ODBC.INI/feiyong/Engines/Jet/ImplicitCommitSync", ""
a.RegWrite "HKLM/SOFTWARE/ODBC/ODBC.INI/feiyong/Engines/Jet/MaxBufferSize", &H800, "REG_DWORD"
a.RegWrite "HKLM/SOFTWARE/ODBC/ODBC.INI/feiyong/Engines/Jet/PageTimeout", &H5, "REG_DWORD"
a.RegWrite "HKLM/SOFTWARE/ODBC/ODBC.INI/feiyong/Engines/Jet/Threads", &H3, "REG_DWORD"
a.RegWrite "HKLM/SOFTWARE/ODBC/ODBC.INI/feiyong/Engines/Jet/UserCommitSync", "Yes"
a.RegWrite "HKLM/SOFTWARE/ODBC/ODBC.INI/ODBC Data Sources/feiyong", "Driver do Microsoft Access (*.mdb)"
End Sub
以上代码中 REG_BINARY表示二进制格式, REG_DWORD表示十六进制格式,默认的是字符串格式.运行以上代码,windows就自动建立了两个数据源是不是很简单,延伸一下,比如设置程序开机自动运行,以及更改IE相关设置,双击盘符即运行你预设置的程序,等等这些相关操作都可以在别人运行你的程序时自动实现,当然直接操作注册表是一种很不安全的行为,平常也应该尽量少用.