我在建立連接和執行數據庫事務的單獨類文件中有下面提到的代碼。我有一個問題,有多個連接正在打開,有時超過連接池。當我瀏覽代碼時,發現有一些代碼在循環中調用ConnectDB()
,但沒有調用DisconnectDB()
。但我預計條件OraConn.State = ConnectionState.Closed
應該處理這種情況。不知何故,條件總是滿足,因此打開另一組連接。你能提出我哪裏會出錯,並且在這裏可以採用哪些最佳做法?用於Oracle多個開放連接的.NET Framework數據提供程序
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
沒有幫助。
UPDATE
我已經把updatedb的代碼中的使用塊下,併除去呼叫ConnectDB和DisconnectDB從功能像InsertData(...)。看來這個問題已經解決了。但是我想知道在例外的情況下,連接是否仍然打開?還有OraConn是在使用塊之外定義的公共變量,所以它會被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
你在哪裏打電話給ConnectDB? – Harsh 2012-01-17 06:57:08
僅使用DataSource,用戶名和密碼創建簡單連接將不起作用。如果您希望能夠重新使用連接啓用池。具體來說,請嘗試啓用'Enlist'和'Pooling'。有關更多詳細信息,請查看[OracleConnection.ConnectionString](http://msdn.microsoft.com/zh-cn/library/system.data.oracleclient.oracleconnection.connectionstring.aspx) – 2012-01-17 07:04:42
@GeekOnDemand我編輯了我的帖子以顯示ConnectDB被稱爲 – Nilanjan 2012-01-17 11:44:46