2014-01-24 54 views
0

如何檢查連接是否已打開mysqlconnection?我想,如果連接已經打開則不需要再次打開它:如何在打開連接之前檢查我的SqlConnection狀態?

Connection = New MySqlConnection() 
Connection.ConnectionString = ConfigurationManager.ConnectionStrings("DbConncetionString").ConnectionString 
Connection.Open() 
SQL = "SELECT * from TBL_PARKERS where id=" & encode(Request.Cookies("parker").Values("id")) & "" 
Dim Query As MySqlCommand = New MySqlCommand(SQL, Connection) 
'Here i want to check connection is open or close 
Connection.Open() 
+0

如果打開它兩次,可能會發生什麼不良嗎?如果「不」,那麼不要打擾。 –

回答

3

鑑於MySqlConnectionDbConnection派生可以例如檢查State財產

Connection.State == ConnectionState.Open 
0

您可以使用此功能進行測試連接。

公共功能TestConn(BYVAL服務器作爲字符串)作爲布爾

Using tcpSocket As New System.Net.Sockets.TcpClient 
     Try 
      Dim async As IAsyncResult = tcpSocket.BeginConnect(server, 1433, Nothing, Nothing) 
      Dim startTime As DateTime = DateTime.Now 

      Do 
       System.Threading.Thread.Sleep(500) 
       If (async.IsCompleted) Then 
        Exit Do 
       End If 
      Loop While (DateTime.Now.Subtract(startTime).TotalSeconds < 5) 

      If (async.IsCompleted) Then 
       tcpSocket.EndConnect(async) 
       Return True 
      End If 
      tcpSocket.Close() 

      If (async.IsCompleted = False) Then 
       Return False 
      End If 

     Catch ex As Exception 

      My.Application.Log.WriteEntry("[" & DateTime.Now & "] - " & ex.Source & ": " & ex.Message) 


     End Try 
    End Using 
End Function 

記住打開的TCP/IP端口號1433

商祺!

相關問題