我使用Access 2003通过ADO访问存储在SQL Server数据库中的数据。通常我使用存储过程获取数据。我通过ADO在一个返回记录集的单独函数中执行存储过程。从函数返回记录集时,哪个是关闭记录集的最佳位置并释放它在内存中的保留?它是在返回记录集的函数中完成的,还是在调用执行ADO代码的函数的子/函数中完成的?这是一个例子......
这是调用方法
Public Sub CallingMethod()
Dim rs As ADODB.Recordset
Set rs = GetDataFromDatabase()
Set myListBox.Recordset = rs
rs.Close
Set rs = Nothing
End Sub
以下是实际执行存储过程并将其返回给调用方法的方法
Public Function GetDataFromDatabase()
Dim cnn As ADODB.Connection
Dim rs As ADODB.Recordset
Set cnn = New ADODB.Connection
cnn.ConnectionString = myConnectionString
cnn.Open
Set rs = New ADODB.Recordset
Set rs.ActiveConnection = cnn
rs.Source = "EXEC uspMyStoredProcedure"
rs.LockType = adLockOptimistic
rs.CursorType = adOpenStatic
rs.CursorLocation = adUseClient
rs.Open
Set GetDataFromDatabase = rs
Set rs = Nothing
Set cnn = Nothing
End Function
我想知道的是我应该关闭记录集并将其设置为空。我是否在两个地方都这样做而不需要?只是寻找最佳实践。谢谢。
答案 0 :(得分:5)
我也不确定正确的是什么。我尝试了一种方法,其中调用代码创建连接对象并将其传递给函数。调用者负责处理连接和记录集对象。它很快&肮脏,因为我不想投入更多,只是为了发现我的方法只是简单的愚蠢。
Public Sub test_GetDataFromSP()
Dim cnn As ADODB.Connection
Dim rs As ADODB.Recordset
Set cnn = New ADODB.Connection
cnn.ConnectionString = "DRIVER=SQL Server;SERVER=VM2003\SQLEXPRESS;" & _
"Trusted_Connection=Yes;DATABASE=Inventory"
cnn.Open
Set rs = GetDataFromSP("GetCenterCodes", cnn, "14, 14, 501")
rs.MoveLast
Debug.Print rs.RecordCount
rs.Close
Set rs = Nothing
cnn.Close
Set cnn = Nothing
End Sub
Public Function GetDataFromSP(ByVal pProc As String, _
ByRef pConnection As ADODB.Connection, _
Optional ByVal pArguments As String) As ADODB.Recordset
Dim rs As ADODB.Recordset
Dim strStatement As String
strStatement = "EXEC " & pProc
If Len(pArguments) > 0 Then
strStatement = strStatement & " " & pArguments
End If
strStatement = strStatement & ";"
Set rs = New ADODB.Recordset
Set rs.ActiveConnection = pConnection
rs.Source = strStatement
rs.LockType = adLockOptimistic
rs.CursorType = adOpenStatic
rs.CursorLocation = adUseClient
rs.Open
Set GetDataFromSP = rs
End Function