微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

VB连接SQL最简单方法

Public conn As ADODB.Connection
Public rs As ADODB.Recordset
Public addFlag As Boolean      '声明部分
Public Function OpenCn(ByVal Cip As String,ByVal users As String,ByVal pw As String,ByVal sjk As String) As Boolean '连接模块 填写数据库等信息
Dim mag As String
On Error GoTo strerrmag
Set conn = New ADODB.Connection
conn.ConnectionTimeout = 25
conn.Provider = "sqloledb"
conn.Properties("data source").Value = Cip     '服务器的名字
conn.Properties("initial catalog").Value = sjk         '库名
'conn.Properties("integrated security").Value = "sspI"      '登陆类型
conn.Properties("user id").Value = users 'sql用户名
conn.Properties("password").Value = pw '密码
conn.Open
OpenCn = True
If conn.State = 1 Then addFlag = True
Exit Function
strerrmag:
     mag = "连接失败!"
     Call MsgBox(mag,vbOKOnly,"错误:")
     addFlag = False
     Exit Function      '连接错误消息
End Function

'关闭数据库,释放连接
Public Sub cloCn()
On Error Resume Next
If conn.State <> adStateClosed Then conn.Close
Set conn = nothing
End Sub

Public Function openRs(ByVal strsql As String) As Boolean      '连接数据库记录集
Dim mag As String
Dim rpy As Boolean
On Error GoTo strerrmag
     Set rs = New ADODB.Recordset
     If addFlag = False Then rpy = True
     With rs
     .ActiveConnection = conn
     .CursorLocation = adUseClient
     .CursorType = adOpenKeyset
     .LockType = adLockOptimistic
     .Open strsql
     End With
     addFlag = True
     openRs = True
     'End        '将记录集给rs
     Exit Function
strerrmag:
     mag = "记录返回错误!"
     Call MsgBox(mag,"错误:")
     openRs = False
     'End
     Exit Function '连接错误消息
End Function
Public Sub cloRs()
On Error Resume Next
If rs.State <> adStateClosed Then rs.Clone
Set rs = nothing '释放记录集
End Sub

原文地址:https://www.jb51.cc/vb/262433.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐