开发者

Handling connection timeout error

Sometimes when my server is down or busy, I get an error saying "connection timeout" while connecting to MySQL. But with the error the 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)

I use this,

开发者_StackOverflow社区
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


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜