I'm dusting off vb.net needs to work and I have a question that I hope you can clarify. My application require a connection with a database, now when the form is load I execute this function:
Sub OpenConnection()
Try
Dim connection As New Connection
Dim MysqlConn = connection.establishConnection()
MysqlConn.Open()
Catch myerror As MySqlException
MessageBox.Show("Connection failed: " & myerror.Message)
Finally
MysqlConn.Dispose()
End Try
End Sub
The problem's that connection
and MysqlConn
variable is used also in another function so I've declared this two variable as global. How you can see this variable are re-declared in the OpenConnection()
'cause I've a form where the user can change the settings connection string. Now if the software can't connect to the database for a wrong credentials the user change this into the setting form but if I remove connection
and MysqlConn
the application use the past instance of a class so even if the credentials are correct, not declaring a new instance of the connection the application can't connect. For the moment I've solved with a re-declaration inside the OpenConnection()
but is this a good move? Is there a way to have the two global variables and invoke a new instance without redefine the function?
Connection class - EstablishConnection function
Public Function establishConnection()
Dim MysqlConn As MySqlConnection = New MySqlConnection()
Dim server_name = My.Settings.server_name
Dim username = My.Settings.username
Dim password = My.Settings.password
Dim database = My.Settings.database
MysqlConn.ConnectionString = "server=" & server_name & ";" _
& "user id=" & username & ";" _
& "password=" & password & ";" _
& "database=" & database & ";"
Return MysqlConn
End Function