【问题标题】:Do I need to close connection when using a 'using' statement [duplicate]使用“使用”语句时是否需要关闭连接[重复]
【发布时间】:2014-11-03 11:48:20
【问题描述】:

目前我的代码构造如下。

using (var sqlCon = new SqlConnection(Context.ReturnDatabaseConnection()))
        {
            sqlCon.Open();

            try
            {
               //Code here

            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            finally
            {
                sqlCon.Close();
            }
        }

根据我的理解,理想情况下,使用 'using' 语句将负责关闭连接,但由于其他人所说的,我对此表示怀疑。

谢谢

【问题讨论】:

标签: c# sqlconnection


【解决方案1】:

当我们使用using 块时,不需要自动处理对象。通过这个

http://msdn.microsoft.com/en-us/library/yh598w02.aspx

What is the C# Using block and why should I use it?

【讨论】:

    【解决方案2】:

    您好,只要 using 语句就可以了。它将处理对象,通常需要较少的编码。

    【讨论】:

      【解决方案3】:

      使用会为您处理好它。作为附加背景,using 语句是 try ... finally 的语法糖,它在 finally 中处理 IDisposable 对象。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-27
        • 2011-05-22
        • 2017-01-31
        • 2013-03-04
        • 1970-01-01
        • 2012-08-15
        • 1970-01-01
        • 2013-05-12
        相关资源
        最近更新 更多