简体   繁体   English

使用ADO .NET在SQL Server上关闭数据库连接

[英]Close database connection on SQL Server using ADO .NET

I'm connecting to database using ADO .NET: 我正在使用ADO .NET连接到数据库:

        Dim conn As SqlConnection
        Dim sqlcmd As SqlCommand
        Dim da As SqlClient.SqlDataAdapter
        Dim table As DataTable

        conn = New SqlConnection(Utilities.ConnectionString)
        sqlcmd = New SqlClient.SqlCommand()
        sqlcmd.Connection = conn
        sqlcmd.CommandType = CommandType.StoredProcedure
        sqlcmd.CommandText = "mySP"
        sqlcmd.Parameters.Add(New SqlClient.SqlParameter("@param", param1))

        da = New SqlClient.SqlDataAdapter()
        da.SelectCommand = sqlcmd
        table = New DataTable()
        da.Fill(table)
        conn.Close()   
        sqlcmd.Connection.Close() 

That works good. 这很好用。 When I launch on SQL Server the command: 当我在SQL Server上启动命令时:

       EXEC SP_WHO2

For each call made from the previous code in ADO .NET, I have in the field Command the value: "AWAITING COMMAND", and in the field Status the value is "sleeping". 对于从ADO .NET中的先前代码进行的每次调用,我在字段Command中输入值:“AWAITING COMMAND”,并在字段Status中,值为“sleeping”。 What does this means? 这意味着什么? The connection to database is still active? 与数据库的连接仍然有效? What should I do in order to close db connection? 我应该怎么做才能关闭数据库连接?

The fact that after few hours you receive errors about connections exausted means that somewhere in your code you don't dispose correctly of your connection. 事实上,在几个小时之后,您会收到有关连接的错误,这意味着您的代码中的某个位置无法正确处理您的连接。
The code above seems correct, but what happen if you have exceptions? 上面的代码似乎是正确的,但是如果你有异常会发生什么? Are you sure to handle correctly the situation when your code exits unexpectedly from a method, due to exceptions? 由于例外原因,当您的代码意外退出某个方法时,您确定能够正确处理这种情况吗?

The correct approach to this situation is refactoring your code. 解决这种情况的正确方法是重构代码。
Introduce everywhere the Using pattern . 随处介绍使用模式 So your code above become: 所以你上面的代码变成:

    Dim conn As SqlConnection 
    Dim sqlcmd As SqlCommand 
    Dim da As SqlClient.SqlDataAdapter 
    Dim table As DataTable 

    Using conn = New SqlConnection(Utilities.ConnectionString) 
        Using sqlcmd = New SqlClient.SqlCommand() 
            sqlcmd.Connection = conn 
            sqlcmd.CommandType = CommandType.StoredProcedure 
            sqlcmd.CommandText = "mySP" 
            sqlcmd.Parameters.Add(New SqlClient.SqlParameter("@param", param1)) 

            da = New SqlClient.SqlDataAdapter() 
            da.SelectCommand = sqlcmd 
            table = New DataTable() 
            da.Fill(table) 
        End Using  
    End Using

This approach will ensure that your disposable objects (connection and command) will be released correctly and you will remove the subtle problem of connection leakings. 这种方法将确保您的一次性物体(连接和命令)将被正确释放,您将消除连接泄漏的微妙问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM