我已經瀏覽了很多關於此問題的文章,以幫助解決此問題,但沒有任何建議似乎有助於關閉我的SQL連接。從VB.net MVC 3.5關閉SQL連接 - 超時問題
這是我使用的VB.net功能:
Private Function InsertOtherProjectMembers(ByVal inProjectRequestId, ByVal inEmployeeId, ByVal inEmployee) As Boolean
Dim reader As SqlDataReader
Using cmd As New SqlClient.SqlCommand
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = objDataClass.Create_Connection()
cmd.CommandText = "usp_InsertOtherProjectMember"
cmd.Parameters.AddWithValue("@ProjectRequestId", inProjectRequestId)
cmd.Parameters.AddWithValue("@EmployeeId", inEmployeeId)
cmd.Parameters.AddWithValue("@Employee", inEmployee)
reader = cmd.ExecuteReader()
reader.Close()
cmd.Connection.Close()
cmd.Dispose()
End Using
End Function
我最近剛添加的使用 - 最終的想法,因爲我發現在這裏使用。我還添加了reader.Close,cmd.Connection.Close,cmd.Dispose。 代碼在Try-Catch-Finally之前。
每次運行這段代碼時,它都會在一個循環中將Employees添加到數據庫中,以便爲每個員工插入一個insert,爲每個員工打開一個到數據庫的連接。被添加的員工名單可能相當長,有時候有30-40名員工。
我想在創建它們之後關閉連接,因爲一旦用戶進行了保存並嘗試在應用程序中加載其他任何內容,我們就會收到一個SQL錯誤,指出存在太多的與數據庫的連接。當我在數據庫上運行sp_who
時,它顯示我與數據庫的連接量增加了一倍,最初可以是2或3,其中包括登錄和加載初始數據,但在運行此插入後,它會上升到15,然後到然後進入30年代。它總是創造新的連接,永遠不會關閉舊的連接。
這是SQL代碼,正在呼籲usp_InsertOtherProjectMember
ALTER PROCEDURE [dbo].[usp_InsertOtherProjectMember]
@ProjectRequestId Varchar(50),
@EmployeeId varchar(5),
@Employee varchar(50)
AS
-- Get the integer part of the transmitted request number
Declare @inReqId AS Int
SET @inReqId = Substring(@ProjectRequestId, 3, Len(@ProjectRequestId)-2)
Insert Into tblProjectRequestOtherMembers(ProjectRequestId, EmployeeId, Employee)
Values(@inReqId, @EmployeeId, @Employee)
還有什麼我要補充在我的代碼/變更,關閉連接?目前,連接只被垃圾收集器關閉,最終......
感謝您的幫助!
編輯: 添加代碼Create_Connection()
Public Function Create_Connection() As Data.SqlClient.SqlConnection
Dim strConn As String
strConn = ConnectionString
Dim Conn As New Data.SqlClient.SqlConnection(strConn)
Conn.Open()
Create_Connection = Conn
End Function
ConnectionString的正在從Webconfig取出並被定義爲公共變量:
ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
在webconfig:
<add name="ConnectionString" connectionString="Server=*SERVERNAME*;Database=*DATABASENAME*;Trusted_Connection=True"/>
另外我想補充一點,這是我繼承的代碼,我是tryi NG修補起來....
'SET @inReqId =子串(@ProjectRequestId,3,LEN(@ProjectRequestId)-2)'這是很糟糕。使'@ ProjectRequestId'成爲'Int'類型,那麼你不必做所有的非認識。也請發佈'objDataClass.Create_Connection()'的代碼...'objDataClass.Create_Connection()'該對象實例是你的問題,它有一個指向該連接(對象)的指針... – Codexer
我做了一個編輯我的代碼與缺少的功能......感謝您的答覆! – bryankerk
我知道這不是答案,但你可以不做以下事情......創建連接....通過添加循環,然後關閉/處置連接一旦循環中的所有添加完成?一個更有效的方法,然後在每次添加後打開和關閉。 – Mych