【发布时间】:2011-09-28 13:32:33
【问题描述】:
我在页面启动并运行时打开和关闭 ODBC 连接。我应该何时何地放置 Connection.Dispose 方法?我在 Page_Disposed 上试过,但它从来没有出现过。
Public Class _WepPage1
Inherits System.Web.UI.Page
Dim MyConnection As New Odbc.OdbcConnection
Private Sub Page_Disposed(sender As Object, e As System.EventArgs) Handles Me.Disposed
MyConnection.Dispose()
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'String comes from Web.Config
MyConnection.ConnectionString = ConfigurationManager.ConnectionStrings("MyConnection").ConnectionString
If Not IsPostBack Then
Call LoadSomeData()
Else
'Do some more stuff
End If
End Sub
Private Sub LoadSomeData()
If MyConnection.State = ConnectionState.Closed Then MyConnection.Open()
Dim MyCommand As New Odbc.OdbcCommand("select * from tablename", MyConnection)
Try
Dim dataR As Odbc.OdbcDataReader = MyCommand.ExecuteReader
While dataR.Read
DropDownList1.Items.Add(dataR("column1"))
End While
Catch ex As Exception
End Try
MyCommand.Dispose()
If MyConnection.State = ConnectionState.Open Then MyConnection.Close()
End Sub
【问题讨论】:
-
可能写在 Try Catch 的 finally 块中
-
当用户进行下拉选择时,我实际上会点击很多数据库,所以我不想在他们关闭应用程序之前释放连接。还是我看错了?
-
你在这里关闭连接,所以我认为没有必要再次处理它。