vb.net 如何在VB 2010中显示数据库连接状态

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22110922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 16:57:07  来源:igfitidea点击:

How to display database connection status in VB 2010

databasevb.netvisual-studio-2010

提问by Geeth

I'm developing Point of sales system. and i want to display database connection status for the users. Im using MS Access 2013 database and Visual Studio 2010 (VB). I created module for this project as follows,

我正在开发销售点系统。我想为用户显示数据库连接状态。我使用 MS Access 2013 数据库和 Visual Studio 2010 (VB)。我为这个项目创建了如下模块,

Imports System.Data.OleDb
Module ModConVar
    Public sql As String
    Public cmd As OleDbCommand
    Public dr As OleDbDataReader

    Public conn As OleDbConnection
    Public connStr As String = System.Environment.CurrentDirectory.ToString & "\NCS_POS_DB.accdb"

    Public Sub ConnDB()
        Try
            conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & connStr & "")
            conn.Open()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub
End Module

And I have a label named lblDBStatus in main MDI form, I tried with followin code, but it dosent work.

我在主 MDI 表单中有一个名为 lblDBStatus 的标签,我尝试使用以下代码,但它不起作用。

If conn.State = ConnectionState.Open Then
    lblDBStatus.Text = "CONECTED"
End If

any suggestions please ??

请问有什么建议吗??

回答by ?s??? ????

You're displaying "CONNECTED" only when the connection state is open. Otherwise your label will not show anything

CONNECTED仅当连接状态为打开时才显示“ ”。否则您的标签将不会显示任何内容

Try this and make sure that the connection is open:

试试这个并确保连接是打开的:

If conn.State = ConnectionState.Open Then
    lblDBStatus.Text = "CONNECTED"
Else 
    lblDBStatus.Text = "DISCONNECTED"
End If

回答by Bj?rn-Roger Kringsj?

The OleDbConnectionexposes a StateChangedevent.

OleDbConnection的暴露了StateChanged事件。

So you can track the state like this:

所以你可以像这样跟踪状态:

Public Sub ConnDB()

    Using connection As New OleDbConnection("...")
        AddHandler connection.StateChange, AddressOf Me.OnConnectionStateChange
        Try
            connection.Open()
            'Do stuff..
        Catch ex As Exception
            Throw ex
        Finally
            RemoveHandler connection.StateChange, AddressOf Me.OnConnectionStateChange
        End Try
    End Using

End Sub

Private Sub OnConnectionStateChange(sender As Object, e As StateChangeEventArgs)
    MessageBox.Show(e.CurrentState.ToString())
End Sub