注册 登录
编程论坛 VB6论坛

连接无法用于执行此操作。在此上下文中它可能已被关闭或无效

leaflet 发布于 2016-06-13 10:02, 6826 次点击
在ACTIVEX DLL里面放置窗体,加一个模块

执行连接SQL

执行查询语句时报错了,如题

程序代码:

'连接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) As Boolean '连接模块 填写数据库等信息
'
On Error GoTo err
    Set conn = New ADODB.Connection

        conn.ConnectionTimeout = 10

        conn.Provider = "sqloledb"
        conn.Properties("data source").Value = Cip     '服务器的名字
        conn.Properties("initial catalog").Value = "DateCenter"      '库名
        'conn.Properties("integrated security").Value = "SSPI"      '登陆类型
        conn.Properties("user id").Value = users
        conn.Properties("Persist Security Info").Value = False
        conn.Properties("password").Value = pw '密码
'
        conn.CursorLocation = adUseServer
        conn.Open
        OpenCn = True
    If conn.State = 1 Then addFlag = True
        Exit Function
'err:
'
      MsgBox err.Number & vbCrLf & err.Description, vbCritical

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 ERR
     Set rs = New ADODB.Recordset
     If addFlag = False Then rpy = True
     With rs

     .ActiveConnection = conn
     .CursorLocation = adUseClient
     .CursorType = adOpenKeyset
     .LockType = adLockOptimistic
'     Debug.Print strsql
     .Open strsql
     End With
     addFlag = True
     openRs = True
     Exit Function
'ERR:
'
'
'调用自定议消息窗口
'
     info
'
     openRs = False
'
     Exit Function
'
'     End
End Function
Public Sub cloRs()
'On Error Resume Next
If rs.State <> adStateClosed Then rs.Clone
Set rs = Nothing '释放记录集
End Sub

3 回复
#2
风吹过b2016-06-13 10:11
1、静态分析,这句是啥意思:
rs.Clone
倒数第三行

2、动态分析,没条件,你的报错是哪一行报错,是从哪里调到哪个函数出错?

3、程序结构分析:
conn 是全局变量,没错,推荐是一个程序一个库只用一个连接。
RS 用全局变量,不建议。RS是随时使用,随时关闭。它的生存期一般建议是用于 函数的生存期,跨函数/过程调用使用按地址传参。

#3
leaflet2016-06-13 10:19
回复 2楼 风吹过b
     .CursorLocation = adUseClient
     .CursorType = adOpenKeyset
     .LockType = adLockOptimistic
'     Debug.Print strsql
     .Open strsql      ------  这句报错   
     End With
#4
leaflet2016-06-13 10:27
回复 2楼 风吹过b
问题找到了,窗体初始化时调用CALL OPENCN写错了
1