Does "using" automatically close SqlConnection

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • John Bailo

    #1

    Does "using" automatically close SqlConnection


    using (
    SqlCommand cmd = new SqlCommand("sel ect * sample"),
    new SqlConnection( sqlDsn )
    )
    )

    {
    SqlDataAdapter adapter = new SqlDataAdapter( cmd);
    DataTable dt = new DataTable();
    adapter.Fill(dt );
    }

    Does the SqlConnection automatically get closed when I exit the using?
  • Sandor Heese

    #2
    Re: Does "using&quo t; automatically close SqlConnection

    In your specific scenario the SqlConnection will be closed but not by the
    using statement. The SqlCommand will close the SqlConnection when it is
    disposed by the using statement.
    The SqlCommand will only close the SqlConnection if it opened the connection
    itself. So if the connection was already open before it was passed as a
    parameter to the SqlCommand it will not be closed by the SqlCommand.

    Sandor

    "John Bailo" <jabailo@texeme .com> wrote in message
    news:_N6dnR6J0c Pv_Wbe4p2dnA@sp eakeasy.net...[color=blue]
    >
    > using (
    > SqlCommand cmd = new SqlCommand("sel ect * sample"),
    > new SqlConnection( sqlDsn )
    > )
    > )
    >
    > {
    > SqlDataAdapter adapter = new SqlDataAdapter( cmd);
    > DataTable dt = new DataTable();
    > adapter.Fill(dt );
    > }
    >
    > Does the SqlConnection automatically get closed when I exit the using?[/color]


    Comment

    Working...