In the first form I will load Tabels in the secound I want to open the DB Connection.
I wrote a Class which enables me to open and close the connection
Imports System
Imports System.Data
Imports MySql.Data.MySqlClient
Public Class DBConn
Dim conn As New MySqlConnection
Dim connString As String
Dim DataSchnitstelel As MySqlDataAdapter
Public Function verbindungString(ByVal Server As String, ByVal UID As String, ByVal PWD As String, _
ByVal Datenbank As String)
connString = "server=" & Server & ";uid=" & UID & ";pwd=" & PWD & ";database=" & Datenbank & ";"
connString = CStr(connString)
End Function
Public Sub Open()
conn.ConnectionString = connString
Try
conn.Open()
MsgBox(connString)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Public Function Close()
If conn.State = ConnectionState.Open Then
Try
conn.Close()
MessageBox.Show("Closed!")
Catch ex As Exception
MessageBox.Show("Something Wrong" & ex.Message)
End Try
Else
MessageBox.Show("Verbindung bereitsgeschlossen")
End If
End Function
Public Function UpdateStatus()
Dim Klank As Boolean
If conn.State = 1 Then
Klank = True
End If
If conn.State = 0 Then
Klank = False
End If
Return Klank
End Function
Public Function SQLSelect()
End Function
End Class
In the Second Form i Connect to the DB. The connection opens successfully but it's not open in the first form :(
Whats Wrong?
If you declare the connection class in each of your forms as Dim someName as new DBConn
, your problem is obvious: they know not of each others existence. If you have a module besides your forms, in which you declare the DBConn instance as Friend, it would be known to all forms
I guess the problem is that you use in both forms somewhere
Dim bla as New DBConn
Instead that, you can make use of the Singleton Pattern. Add the following code inside your DBConn class:
'Make Constructor Private to disallow creating an Instance from somewhere else
Private Sub New()
End Sub
'Variable to share the only created instance
Private Shared _Instance As DBConn
'Function to get access to the only instance
Public Shared ReadOnly Property Instance() As DBConn
Get
If _Instance Is Nothing Then
_Instance = New DBConn
End If
Return _Instance
End Get
End Property
After those changes, you need to 'correct' one line in each form to the following:
Dim bla as DBConn = DBConn.Instance
This should assure that both forms are asking for an instance, and only the very first time an instance is created. All further askings receive the same instance.
One more thing: If you have 'WithEvents' or any EventHandling connected to that Singleton, then make sure to set your DBConn variable to nothing when you close/dispose form1. But according to your code this does not matter.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.