代码之家  ›  专栏  ›  技术社区  ›  rjrapson

是否使用关闭打开的SQL连接结束

  •  62
  • rjrapson  · 技术社区  · 17 年前

    如果我在Using中包装一个SQLConnection,我应该关闭它还是使用结束来处理它?

    using cn as new system.data.sqlclient.sqlconnection()
        cn.open
        '{do a bunch of other stuff with commands and datareaders here}
        cn.close 'Do I need this?
    end using 
    
    6 回复  |  直到 17 年前
        1
  •  96
  •   matt b    17 年前

    正在使用有关对象的block calls.Dispose()退出( cn 在您的示例中),对于SqlConnection,将关闭连接和所有打开的资源。

        2
  •  31
  •   Darin Dimitrov    17 年前

    更准确地说,调用Dispose或Close会将底层物理连接标记为“未使用”——但不会真正关闭它。因此,尚未物理关闭的“未使用”连接可用于池。因此,调用Dispose将返回到连接池的连接。

        3
  •  12
  •   Hector Correa    15 年前
        4
  •  4
  •   Bryan Anderson    17 年前

        5
  •  2
  •   michaeldavid    10 年前

    Using块的行为类似于Try…Finally构造,其中Try块使用资源,Finally块处理资源。因此,Using块保证资源的处理,无论您如何退出该块。即使在未处理的异常情况下也是如此,StackOverflowException除外
    https://msdn.microsoft.com/en-us/library/htd05whh.aspx

        6
  •  1
  •   Matt Briggs    17 年前

    Try
        SqlConnection cn as new system.data.sqlclient.sqlconnection()
        cn.open
        '{do a bunch of other stuff with commands and datareaders here}
        cn.close 'Do I need this?
    Finally
        cn.Dispose()
    End Try
    

    Dispose应该负责所有资源清理,在连接的情况下,它将关闭它。

    推荐文章