tags:

views:

136

answers:

2

Hi

sometimes when my server is down or busy, i get error telling "connection timeout" while connecting to MYSQL. but with the error program also crashes. my question is how can i prevent crashing, it would be better to show a msgbox when this happens. (visual basic 2010)

here is a screenshot of the error alt text

i use this,

Dim connStr As String = "Database=mydatabase;" & _
                    "Data Source=datasrc;" & _
                    "User Id=myid;Password=mypass"

    Dim connection As New MySqlConnection(connStr)

            connection.Open() // i get error here

thank you

A: 

One way this can happen is if you don't properly dispose your connections. For example, say an exception is thrown due to a problem in your sql code, and it's caught, but caught in such a way that you never call connection.Close(). Eventually you will run out of available connections and your connection.Open() call will fail and timeout when trying to connect. To avoid this, you should create your connections with a "using" block, like this:

Using connection As New MySqlConnection(connStr), _
      command As New MySqlCommand("sql statement here")

    connection.Open()


End Using ''# connection is guaranteed to be closed here, even if an exception is thrown
Joel Coehoorn
it doesnt work when i call connection function second time, i still get error
Ahmet vardar
+1  A: 

If you don't want to see the ThreadExceptionDialog, you'll need to catch the exception in your code. For example:

  Public Function ConnectToDbase() As Boolean
    Try
      connection.Open()
      '--- etc
      Return True
    Catch ex As TimeoutException
      MessageBox.Show(ex.Message, "Could not connect to the database")
      Return False
    End Try
  End Function

The burden is now on the code that uses ConnectToDbase() to do something meaningful when it returns False.

Hans Passant
thanks it works but this time i get almost 20 msgbox.
Ahmet vardar
That's the "do something meaningful" burden I talked about. Don't keep trying to use the dbase when you got a False return. Maybe you ought to tell the user to call support and terminate your program.
Hans Passant