How to close connection?

Last post 11-07-2009 12:34 PM by TATWORTH. 3 replies.

Sort Posts:

  • How to close connection?

    11-02-2009, 3:04 PM
    • Participant
      1,873 point Participant
    • aspfun
    • Member since 04-15-2004, 9:05 PM
    • Posts 756

    I used code below to close connection, is it right?

          Try
                myConn.Open()
                mySQLCommand.ExecuteNonQuery()
            Catch ex As Exception
               'code to display error message
            Finally
                myConn.Close()
                 mySQLCommand.Dispose()
                myConn.Dispose()
            End Try

    Does it need "  mySQLCommand.Dispose()"?

  • Re: How to close connection?

    11-02-2009, 3:11 PM
    • Participant
      845 point Participant
    • crawford.r
    • Member since 08-10-2009, 3:01 PM
    • Posts 169

    That should work fine; but it is doing some extra work. myConn.Dispose() will automatically call myConn.Close(), so myConn.Close() is not needed. As for mySQLCommand.Dispose(), it isn't absolutely necessary, but it's probably a good idea to keep it.

    http://social.msdn.microsoft.com/Forums/en-US/adodotnetdataproviders/thread/916a1734-3e19-43a1-95c7-e3a2cd18369d

  • Re: How to close connection?

    11-02-2009, 3:19 PM
    Answer
    • All-Star
      24,944 point All-Star
    • budugu
    • Member since 01-12-2006, 2:15 PM
    • North Carolina
    • Posts 3,726

    Even better..It saves you the hassle of manually creating the try / finally block and calling Dispose().

    Using cn As New SqlConnection(myConn) 
    
        Using cm As New SqlCommand(mySQLCommand, cn) 
    
            cn.Open() 
    
            cm.ExecuteNonQuery() 
    
        End Using 
    
    End Using 
    


    Refer this.. http://davidhayden.com/blog/dave/archive/2005/01/13/773.aspx

    Vijay Kodali || My Blog


    "Don't be afraid to be wrong; otherwise you'll never be right."
  • Re: How to close connection?

    11-07-2009, 12:34 PM
    • All-Star
      62,662 point All-Star
    • TATWORTH
    • Member since 02-04-2003, 8:34 AM
    • England
    • Posts 12,229
    • TrustedFriends-MVPs

    >Does it need "  mySQLCommand.Dispose()"?

    One way of finding out is to run FXCOP with and wiithout the line commented out. You can get FXCOP from  http://www.microsoft.com/downloads/details.aspx?FamilyID=9aeaa970-f281-4fb0-aba1-d59d7ed09772&DisplayLang=en

    Don't forget to click "Mark as Answer" on the post that helped you.
    This credits that member, earns you a point and marks your thread as Resolved so we will all know you have been helped.
Page 1 of 1 (4 items)