【问题标题】:How do I check my SqlConnection state before open connection?在打开连接之前如何检查我的 SqlConnection 状态?
【发布时间】:2014-01-24 09:32:13
【问题描述】:

如何检查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()

【问题讨论】:

  • 打开两次会不会有什么不好的事情发生?如果“不”,那就不要打扰。

标签: asp.net vb.net sqlconnection


【解决方案1】:

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

Connection.State == ConnectionState.Open

【讨论】:

    【解决方案2】:

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

    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。

    问候!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-25
      • 1970-01-01
      • 1970-01-01
      • 2015-09-11
      • 1970-01-01
      • 1970-01-01
      • 2016-01-07
      • 1970-01-01
      相关资源
      最近更新 更多