如何在打开连接之前检查我的SqlConnection状态?

时间:2014-01-24 09:32:14

标签: asp.net vb.net sqlconnection

如何使用mysqlconnection检查连接是否已打开?我希望如果连接已经打开,则无需再次打开它:

 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()

2 个答案:

答案 0 :(得分:3)

鉴于MySqlConnection来自DbConnection,您可以检查State属性,例如

Connection.State == ConnectionState.Open

答案 1 :(得分:0)

您可以使用此功能进行测试连接。

Public Function TestConn(ByVal server As String)As Boolean

    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。

问候!