我为什么要关闭并销毁记录集?

时间:2014-03-10 15:54:10

标签: asp-classic adodb recordset

我读过这篇文章:http://www.utteraccess.com/wiki/Recordsets_for_Beginners,它说我关闭并摧毁RS是很重要的: rs.close Set rs = Nothing
如果我不这样做,可能会发生一些错误。

  1. 什么样的错误?
  2. rs.close的含义是什么?是否意味着只要rs未关闭,与数据库的连接就会保持打开状态?

2 个答案:

答案 0 :(得分:4)

T McKeown says绝对正确

根据您返回的ADODB.Recordset的类型,您最终可能会遇到一些不必要的开销。 Call rs.Close()的目的是消除这些开销,这些开销不需要大多数数据检索。

以这个例子为例,在页面开头定义的连接在页面的整个生命周期中都有。

Dim conn, conn_string, rs

conn_string = "some connection string to your database"

'Memory allocated for ADODB.Connection object
Set conn = Server.CreateObject("ADODB.Connection")
'Connection opened to data source (SQL Server, Oracle, MySQL etc)
Call conn.Open()

Set rs = conn.Execute("SELECT * FROM [sometable]")
Do While Not rs.EOF
  'Long running page (do some processing)
  Call rs.MoveNext()
Loop

'Remove any locks on the tables and dis-associate connection
Call rs.Close()
'Deallocate ADODB.Recordset from memory
Set rs = Nothing

'Connection is still open and needs to be closed
Call conn.Close()
'Connection closed but still allocated in memory
Set conn = Nothing

多年来,我发现使用数组来显示数据效率更高,并节省了ADODB对象的开销。

Dim conn, conn_string, rs, cmd, data

conn_string = "some connection string to your database"

'Memory allocated for ADODB.Command object
Set cmd = Server.CreateObject("ADODB.Command")
With cmd
  'Connection allocated when ADODB.Command is run and only
  'lasts for the life of ADODB.Command object.
  .ActiveConnection = conn_string
  .CommandType = adCmdText
  .CommandText = "SELECT * FROM [sometable]"
  'Allocate memory for ADODB.Recordset
  Set rs = .Execute()
  'Use .GetRows() to build a two dimensional array 
  'containing the ADODB.Recordset data.
  If Not rs.EOF Then data = rs.GetRows()
  Call rs.Close()
  'Deallocate memory for ADODB.Recordset
  Set rs = Nothing
End with
'Deallocate ADODB.Command which closes and de-allocates
'the associated  ADODB.Connection.
Set cmd = Nothing

'All ADODB objects have been deallocated rest of the page can run
'without them using the array to iterate through the data.
If IsArray(data) Then
  'Long running page (do some processing)
End If

有关在数组中处理数据的更多信息,请参阅this answer到另一个问题,给出的示例包含使用数组迭代数据的示例。

答案 1 :(得分:2)

rs.close清理内部使用的资源,但是因为ASP是一个没有任何GC的单个进程Set rs = Nothing有助于清理。

它取消引用你的对象,没有它你就会有内存泄漏。好不是吗?