我在一个单独的类文件中有下面提到的代码,用于建立连接和执行数据库事务。我有一个问题,即打开的多个连接有时超过了连接池。当我单步执行代码时,我发现有些代码ConnectDB()
在循环中调用而不调用DisconnectDB()
. 但我预计条件OraConn.State = ConnectionState.Closed
应该处理这种情况。不知何故,条件总是得到满足,因此打开了另一组连接。您能否建议我在哪里出错以及可以在这里采用哪些最佳实践?
Public Class Connection
Dim Str_conn As String = "Data Source=...; User=...; password=...; Min Pool Size=10; Max Pool Size=500;"
Public OraConn As OracleConnection
Dim cmd As OracleCommand
Dim dr As OracleDataReader
Dim data_adapt As OracleDataAdapter
Dim dt As DataTable
Dim ds As DataSet
Public Sub ConnectDB()
OraConn = New OracleConnection(Str_conn)
If OraConn.State = ConnectionState.Closed Then
OraConn.Open()
End If
End Sub
Public Sub DisconnectDB()
If OraConn.State = ConnectionState.Open Then
OraConn.Close()
End If
End Sub
Public Function get_dataset(ByVal query As String, ByRef ds As DataSet) As DataSet
data_adapt = New OracleDataAdapter(query, OraConn)
data_adapt.Fill(ds)
Return ds
End Function
Public Function get_datareader(ByVal query As String) As OracleDataReader
cmd = New OracleCommand(query, OraConn)
dr = cmd.ExecuteReader()
Return dr
End Function
Public Sub UpdateDB(ByVal query As String)
cmd = New OracleCommand(query, OraConn)
cmd.ExecuteNonQuery()
cmd.Dispose()
End Sub
该类在其他类中或直接在 aspx.vb 页面中引用,就像这样。
Public Function InsertData(ByVal var1 As String, ByVal var2 As String) As Integer
conn.ConnectDB()
Dim qryInsert As String
qryInsert = " INSERT INTO TABLE VALUES ('" & var1 & "', "
qryInsert = qryInsert & var2 & "')"
Try
conn.UpdateDB(qryInsert)
Catch ex As OracleException
If ex.Code = 1 Then
updData(var1, var2)
ElseIf ex.Code = 2091 Then
msgprompt("Duplicate Unique Key!", "Warning")
End If
Finally
conn.DisconnectDB()
End Try
Return count
End Function
连接再次在函数中打开updData()
。虽然我知道它必须正确关闭,但不可能密切关注每个开发人员。因此,我想通过使用相同的连接直接从连接类控制它,但条件If OraConn.State = ConnectionState.Closed
没有帮助。
更新
我已将代码放在 UpdateDB 中的 Using 块下,并从 InsertData(...) 之类的函数中删除了对 ConnectDB 和 DisconnectDB 的调用。看来问题已经解决了。但我想知道如果出现异常,连接会保持打开状态吗?而且 OraConn 是在 Using 块之外定义的公共变量,所以它会被 GC 处理掉吗?
Public Sub UpdateDB(ByVal query As String)
Using OraConn = New OracleConnection(Str_conn)
cmd = New OracleCommand(query, OraConn)
Try
OraConn.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
Throw
Finally
cmd.Dispose()
End Try
End Using
End Sub