Function getConn(Provider, DataSource, UserName, PassWord, Host)
On Error Resume Next
Dim SQLConnStr
Set getConn = Nothing
Set getConn = CreateObject("ADODB.Connection")
If Host = "" Or IsNull(Host) Or IsEmpty(Host) Then Host = "(local)"
If UserName = "" Or IsNull(UserName) Or IsEmpty(UserName) Then UserName = "sa"
If IsNull(PassWord) Or IsEmpty(PassWord) Then PassWord = ""
If Provider <> "SQL" Then
'使用MS-Access来链接
SQLConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & DataSource
Else
'采用SQL数据库来链接
SQLConnStr = "Provider=SQLOLEDB.1;User ID=" & UserName & ";Password=" & PassWord & ";Initial Catalog=" & DataSource & ";Data Source= " & Host
End If
getConn.open SQLConnStr
If Err.Number <> 0 Then
Set getConn = Nothing
Err.Clear
End If
End Function
在调用时,如果要与SQL数据库链接,就这样:
Set MyConn=getConn("SQL", 数据库名, 用户名, 用户密码, SQL主机)
如果要与MS - Access链接:
Set MyConn=getConn("MS", 数据库名, '', '', '')