一個用VB連接SQL數(shù)據(jù)庫連接的模塊!
發(fā)布時間:2008-08-11 閱讀數(shù): 次 來源:網(wǎng)樂原科技
下面是一個連接數(shù)據(jù)庫的模塊,大家可以使用它來連接SQL數(shù)據(jù)庫,使用起來比ADO控件還簡單:
代碼如下:
Public rsNew As ADODB.Recordset
Public CnNew As ADODB.Connection
Public addFlag As Boolean
'連接數(shù)據(jù)庫
Public Function OpenCn() As Boolean
Dim Mag As String
On Error GoTo strErrMag
Set CnNew = New ADODB.Connection
CnNew.ConnectionTimeout = 25
CnNew.Provider = "sqloledb"
CnNew.Properties("data source").value = "" 'SQL服務器的名
CnNew.Properties("initial catalog").value = "pubs"'庫名
CnNew.Properties("integrated security").value = "SSPI"'登陸類型
'con.Properties("user id").value = "sa"
'con.Properties("password").value = "wwww"
CnNew.Open
OpenCn = True
addFlag = True
Exit Function
strErrMag:
Mag = "數(shù)據(jù)庫末連接"
Call MsgBox(Mag, vbOKCancel, "錯誤:數(shù)據(jù)庫連接")
addFlag = False
End
End Function
Public Sub Clocn()
'閉關數(shù)據(jù)庫
On Error Resume Next
If CnNew.State <> adStateClosed Then CnNew.Close
Set CnNew = Nothing
End Sub
Public Function OpenRs(ByVal strSql As String) As Boolean
'連接數(shù)據(jù)庫記錄集
Dim Mag As String
Dim rpy As Boolean
On Error GoTo strErrMag
Set rsNew = New ADODB.Recordset
If addFlag = False Then rpy = OpenCn
With rsNew
.ActiveConnection = CnNew
.CursorLocation = adUseClient
.CursorType = adOpenKeyset
.LockType = adLockOptimistic
.Open strSql
End With
addFlag = True
OpenRs = True
Exit Function
strErrMag:
Mag = "數(shù)據(jù)庫數(shù)據(jù)集末連接"
Call MsgBox(Mag, vbOKOnly, "錯誤:數(shù)據(jù)庫連接")
OpenRs = False
End
End Function
Public Sub cloRs()
'閉關數(shù)據(jù)集
On Error Resume Next
If rsNew.State <> adStateClosed Then rsNew.Close
Set rsNew = Nothing
End Sub
只要在你的標準模塊中加入該代碼,你就可以使用其中的函數(shù)來連接數(shù)據(jù)源了。