我正在开发销售点系统。我想显示用户的数据库连接状态。我使用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
我在主MDI表单中有一个名为lblDBStatus的标签,我尝试使用以下代码,但它起作用了。
If conn.State = ConnectionState.Open Then
lblDBStatus.Text = "CONECTED"
End If
有什么建议吗?
答案 0 :(得分:0)
仅在连接状态打开时才显示“CONNECTED
”。否则你的标签不会显示任何内容
尝试此操作并确保连接已打开:
If conn.State = ConnectionState.Open Then
lblDBStatus.Text = "CONNECTED"
Else
lblDBStatus.Text = "DISCONNECTED"
End If
答案 1 :(得分:0)
OleDbConnection公开StateChanged事件。
所以你可以跟踪这样的状态:
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