How to add Failover Partner to a connection string in VB.NET

后端 未结 3 440
闹比i
闹比i 2020-12-10 08:52

I have a windows application connecting to Database to read some data. Since the database is setup for resilience, my application needs to connect to one of the two database

3条回答
  •  遥遥无期
    2020-12-10 09:26

    If you do not have mirroring set up between SQL servers, you can achieve this by using .net. simply in a catch statement.

    Code below..

    enter code here
    Imports System.Data.SqlClient
    Imports System.Data
    
    Public Class dbConn
    Private primaryServerLocation As String = "SERVER=primaryAddress;DATABASE=yourDB;User id=youruserID;Password=yourPassword;"
    Private secondaryServerLocation As String = "SERVER=secondaryAddress;DATABASE=yourDB;User id=youruserID;Password=yourPassword;"
    
    
    Public sqlConnection As SqlConnection
    Public cmd As SqlCommand
    
    Public Sub primaryConnection()
        Try
            sqlConnection = New System.Data.SqlClient.SqlConnection(primaryServerLocation)
            cmd = New System.Data.SqlClient.SqlCommand()
    
            'test connection
            sqlConnection.Open()
            sqlConnection.Close()
        Catch ex As Exception
            secondaryConnection()
        End Try
    End Sub
    
    Public Sub secondaryConnection()
        'Used as the failover secondary server if primary is down.
        Try
            sqlConnection = New System.Data.SqlClient.SqlConnection(secondaryServerLocation)
            cmd = New System.Data.SqlClient.SqlCommand()
    
            'test connection
            sqlConnection.Open()
            sqlConnection.Close()
        Catch ex As Exception
        End Try
    End Sub
    End Class
    

提交回复
热议问题