读书人

多次调用Recordset的有关问题

发布时间: 2012-03-09 21:42:54 作者: rapoo

多次调用Recordset的问题
各位,请教一个问题,我在一个模块中定义了一个通用的ADO Recordset通用函数openrs,现在发现同一个问题:
在其他函数/过程调用openrs时,如果该函数/过程只调用openrs一次的话,可以得到正确的数据,如果多次调用openrs的话,无论多少次都只能得到第一次调用的结果;是否ADO Recordset的recordset不支持这样的连续调用?set rs = nothing ,rs.close那些都试过了,还是一样;

具体为:函数Count_GW,两次调用openrs,第一次是count_f,第二次是count_t ,但Count_GW得到的数据只是两个count_f的相加,count_t得不到数据,就是第二次调用recordset时,数据不能进行更新传递;
如果将count_f 和count_t分为两个函数进行计算,就能得到正确的结果,测试了好久不知道原因,请各们高手指点一二,谢谢!

代码如下:
**********Openrs 相关:

Public Function DBconnect()
cnn.ConnectionString = "Provider = microsoft.jet.oledb.4.0;persist security info = false;data source = " & PJPath & "\TestDB.mdb;jet oledb:DataBase password = "
cnn.Open
End Function

Public Function DBDisconnect()
cnn.Close
Set cnn = Nothing
End Function

Public Function OpenRS(ByVal sqlstmt As String) As ADODB.Recordset
Dim rst As New ADODB.Recordset
DBconnect
rst.ActiveConnection = cnn
rst.Open sqlstmt
Set OpenRS = rst
End Function

**********调用openrs的程序
Public Function Count_GW() 'count gross weight
On Error Resume Next
Dim Rs_Count As New ADODB.Recordset
Dim Count_f, Count_t As Single
Count_f = 0
Count_t = 0
sql_f = "select SUM([GW(kgs)]) from [fabric details]"
sql_t = "select SUM([GW(kgs)]) from [packing list]"

Set Rs_Count = OpenRS(sql_f)
If Rs_Count(0).Value > 0 Then
Count_f = Rs_Count(0).Value
End If
Set Rs_Count = OpenRS(sql_t)
If Rs_Count(0).Value > 0 Then
Count_t = Rs_Count(0).Value
End If

Count_GW = Count_f + Count_t
Rs_Count.Close
Set Rs_Count = Nothing
DBDisconnect
End Function


[解决办法]
Public Function OpenRS(ByVal sqlstmt As String) As ADODB.Recordset
Dim rst As New ADODB.Recordset
If cnn.State = adStateOpen Then
cnn.Close
Set cnn = Nothing
End If
DBconnect
rst.ActiveConnection = cnn
rst.Open sqlstmt
Set OpenRS = rst
End Function

经测试,正常.

[解决办法]
Public Function OpenRS(ByVal sqlstmt As String) As ADODB.Recordset
Dim rst As New ADODB.Recordset
DBconnect'问题根源,再次打开连接之前,应该先关闭cnn
rst.ActiveConnection = cnn
rst.Open sqlstmt
Set OpenRS = rst
End Function

读书人网 >VB

热点推荐