从VB.net MVC 3.5关闭SQL连接 - 超时问题

时间:2016-04-01 13:33:21

标签: sql-server vb.net timeout connection

我已经在这里查看了很多帖子以获得有关此问题的帮助,但似乎没有任何建议可以帮助我关闭SQL连接。

这是我在VB.net中使用的功能:

.meteor/local/db

我最近刚刚添加了使用 - 结束使用因为我在这里找到的想法。我还添加了reader.Close,cmd.Connection.Close,cmd.Dispose。 在代码进入Try-Catch-Finally之前。

每次运行此代码时,它都会将Employees添加到循环中的数据库中,因此它会为每个员工执行插入操作,为每个员工打开与数据库的连接。添加的员工名单可能很长,有时候是30-40名员工。

我尝试在创建连接后关闭它们,因为一旦用户执行了保存并尝试加载应用程序中的任何其他内容,我们就会收到一条SQL错误,指出与数据库的连接太多。当我在数据库上运行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 时,它向我显示了与数据库的增量连接,最初它可以是2或3,其中包括登录和加载初始数据,但在我运行此插入后,它会上升到15然后到20ish然后进入30's。它总是创造新的联系,永远不会关闭旧的。

这是为usp_InsertOtherProjectMember

调用的SQL代码
sp_who

我的代码还有什么要添加/更改以关闭连接吗?目前,连接仅由垃圾收集器关闭,最终......

感谢您的帮助!

编辑: 为Create_Connection()添加代码

    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)

ConnectionString来自Webconfig,被定义为公共变量:

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

在webconfig中:

ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString

另外我想补充一点,这是我继承的代码,我正在尝试修补它....

1 个答案:

答案 0 :(得分:0)

请试一试......

Public Shared Function Create_Connection() As String
    Return ConnectionString 'Just return the connection string...
End Function

Using cmd As New SqlClient.SqlCommand
  Using con As New SqlClient.SqlConnection(Create_Connection())
            cmd.CommandType = CommandType.StoredProcedure
            cmd.Connection = con 'use the con which is your connection now...
            cmd.CommandText = "usp_InsertOtherProjectMember"
            cmd.Parameters.AddWithValue("@ProjectRequestId", inProjectRequestId)
            cmd.Parameters.AddWithValue("@EmployeeId", inEmployeeId)
            cmd.Parameters.AddWithValue("@Employee", inEmployee)

            con.Open()
            reader = cmd.ExecuteReader()
            reader.Close()
            con.Close()
  End Using
End Using