Search code examples
vb.netsqlconnectionusing-statement

should use using/end using or manually close sqlConnection


in the following methods which is the suitable to work with SQL

Method 1

Using conn As New SqlConnection("....")
     conn.Open()
     '/to do
End Using

Method 2

Try
   dim conn as new sqlconnection =("....")
   conn.open()
   '/to do
Catch
   MsgBox("ex.message")
Finally
   conn.close()
End Try

Solution

  • Method 1 is more usual, since Method 2 mixes data access (opening a database connection) and presentation (displaying a message to the user).

    It's more usual to separate your application into presentation, business logic, and data access tiers. E.g.

    ... Presentation code
    Try
        BusinessLogic.SaveData(...)
    Catch
        MsgBox...
    End Try
    
    ... BusinessLogic tier
    Public Sub SaveData(...)
        DataAccess.SaveData(...)
    End Sub
    
    ... Data access tier
    Public Sub SaveData(...)
        Using conn As New SqlConnection("....")
            ...
        End Using
    End Sub
    

    Also note that you should generally only catch exceptions if you can handle them. Therefore the business logic and data access tiers should rarely use a Catch block - they just let Exceptions propagate to the presentation tier. The presentation tier may be able to handle exceptions (e.g. display a mesage to the user and let them retry), so may contain a Catch block.