In addition to what OriginalGriff suggested, you can automate this rather than changing your code all of the time to ensure a successful connection -
You need to dynamically adjust your connection settings based on the specific database version you are trying to connect to, as an example, you might need to set specific options or features depending on the database version -
Imports System.Data.SqlClient
Public Class DatabaseConnector
Private connectionStringTemplate As String
Public Sub New(serverName As String, databaseName As String, username As String, password As String)
connectionStringTemplate = $"Data Source={serverName};Initial Catalog={databaseName};User ID={username};Password={password};"
End Sub
Public Function OpenConnection() As SqlConnection
Dim connection As New SqlConnection()
Try
Dim databaseVersion As String = GetDatabaseVersion()
Dim connectionString = String.Format(connectionStringTemplate, databaseVersion)
connection.ConnectionString = connectionString
connection.Open()
Console.WriteLine("Connection opened successfully.")
Catch ex As Exception
Console.WriteLine($"Error opening connection: {ex.Message}")
End Try
Return connection
End Function
Public Sub CloseConnection(connection As SqlConnection)
Try
connection.Close()
Console.WriteLine("Connection closed.")
Catch ex As Exception
Console.WriteLine($"Error closing connection: {ex.Message}")
End Try
End Sub
Private Function GetDatabaseVersion() As String
Return "v1.0"
End Function
End Class