Question

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
Was it helpful?

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.

OTHER TIPS

I would recommend that you always use a Try block when you attempt to call the Open method of an SqlConnection object and that you explicitly call the Close method when you are finished. Obviously that needs to be done before the connection object goes out of scope at the end of a method or Using block (if it is indeed locally declared).

The use of a Using block depends on the scope that you require for your SqlConnection object.

Also I would call the Close method in another Try block rather than in the Finally section.

And you are calling the string literal "ex.message" which is what will be displayed rather than the error message.

Using conn As New SqlConnection("....")

    Try
        conn.open()

    Catch ex As Exception
        MessageBox.Show(ex.Message)
        Return

    Catch SqlEx As SqlException
        MessageBox.Show(SqlEx.Message)
        Return

    End Try

    'do data processing here using the conn object etc

    Try

        conn.close()

    Catch ex As Exception

    Catch SqlEx As SqlException

    End Try

End Using
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top