注册 登录
编程论坛 VB6论坛

对象关闭时不允许操作

lz_xiaohai 发布于 2017-12-26 09:22, 3660 次点击
1、
Public Sub main()            '定义一个公共主函数,用于连接数据库
    cnnstr = "Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;PWD=itxrgw;Initial Catalog=db_SPJXC;Data Source=."
    cnn.Open (cnnstr)
End Sub
2、
Private Sub Toolbar1_ButtonClick(ByVal Button As MSComctlLib.Button)
    Select Case Button.Key
    Case "add"   '添加

    Case "del"    '删除

    Case "save"   '保存

        Call main
        cnn.Execute ("insert into 经手人表 values('" & Text1(0).Text & "','" & Text1(1).Text & "','" & Text1(2).Text & "','" & Text1(3).Text & "','" & Text1(4).Text & "','" & Text1(5).Text & "')")
        Set rs = ExecuteSQL("select * from 经手人表")
        Set DataGrid1.DataSource = rs
        DataGrid1.Refresh
        Set rs = Nothing
        cnn.Close
        rs.Close

    Case "cancel"  ' 取消
   
'    Case "find"    ' 查询

'    Case "close"   '关闭

    End Select
End Sub
3、如果我要程序随时执行cnn.execute  模块需要怎么设置
像执行查询一下,随时调用 ExecuteSQL(sql)。
Public Function ExecuteSQL(ByVal sql As String) As ADODB.Recordset

    Dim rs As New ADODB.Recordset
    Dim cnn As New ADODB.Connection

    cnn.Open "Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;pwd=itxrgw;Initial Catalog=db_SPJXC"
    rs.Open Trim(sql), cnn, adOpenKeyset, adLockOptimistic
    Set ExecuteSQL = rs
End Function
4 回复
#2
lz_xiaohai2017-12-26 10:17
回复 楼主 lz_xiaohai
Private Sub Toolbar1_ButtonClick(ByVal Button As MSComctlLib.Button)
    Select Case Button.Key
    Case "add"   '添加

    Case "del"    '删除

    Case "save"   '保存

        cnn.Open "Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;pwd=itxrgw;Initial Catalog=db_SPJXC"
        cnn.Execute ("insert into 经手人表 values('" & Text1(0).Text & "','" & Text1(1).Text & "','" & Text1(2).Text & "','" & Text1(3).Text & "','" & Text1(4).Text & "','" & Text1(5).Text & "')")
        Set rs = ExecuteSQL("select * from 经手人表")
        Set DataGrid1.DataSource = rs
        DataGrid1.Refresh
        Set rs = Nothing
        cnn.Close
        rs.Close

    Case "cancel"  ' 取消
   
'    Case "find"    ' 查询

'    Case "close"   '关闭

    End Select
End Sub

这样的话是可以执行的,为什么调用模块里的连接就不行,直接把连接写到程序里就可以?
#3
xzlxzlxzl2017-12-26 11:02
在模块中定义一个全局的cnn,如下:
public cnn As New ADODB.Connection
#4
lz_xiaohai2017-12-26 12:32
现在可以了。谢谢各位了。

[此贴子已经被作者于2017-12-27 14:15编辑过]

#5
ZHRXJR2018-01-02 18:06
        Set rs = Nothing
        cnn.Close
        rs.Close
rs对象、cnn对象的关系你没有搞清除,cnn对象是连接数据库的对象,rs对象是记录集对象。
你的这三个语句是:
        Set rs = Nothing   '从内存清除rs对象
        cnn.Close          '关闭cnn对象
        rs.Close           '关闭rs对象,既然已经从内存清除了,而且cnn对象已经关闭了,你认为rs对象还存在吗?估计问题就出在这一句!

应该是这样的顺序关系:
        rs.Close           '关闭rs对象
        Set rs = Nothing   '从内存清除rs对象
        cnn.Close          '关闭cnn对象
        Set cnn = Nothing  '从内存清除cnn对象


[此贴子已经被作者于2018-1-2 18:09编辑过]

1