我有一个连接到数据库的 Windows 应用程序来读取一些数据。由于数据库是为弹性设置的,我的应用程序需要连接到两个数据库之一。有人可以指定使用 sql server 身份验证在连接字符串中指定故障转移伙伴的语法是什么。
任何帮助是极大的赞赏。
我有一个连接到数据库的 Windows 应用程序来读取一些数据。由于数据库是为弹性设置的,我的应用程序需要连接到两个数据库之一。有人可以指定使用 sql server 身份验证在连接字符串中指定故障转移伙伴的语法是什么。
任何帮助是极大的赞赏。
数据库镜像
如果您使用 ADO.NET 或 SQL Native Client 连接到正在镜像的数据库,您的应用程序可以利用驱动程序在数据库镜像故障转移发生时自动重定向连接的能力。您必须在连接字符串中指定初始主体服务器和数据库以及故障转移伙伴服务器。
Data Source=myServerAddress;Failover Partner=myMirrorServerAddress;Initial
Catalog=myDataBase;Integrated Security=True;
当然还有许多其他方法可以使用数据库镜像来编写连接字符串,这只是指出故障转移功能的一个示例。您可以将其与其他可用的连接字符串选项结合使用。
如果您在连接字符串中提供故障转移伙伴服务器的名称,并且在客户端应用程序首次连接时主体数据库不可用,客户端将透明地尝试与故障转移伙伴建立连接。
";Failover Partner=PartnerServerName"
如果您省略了故障转移伙伴服务器的名称,并且在客户端应用程序首次连接时主体数据库不可用,则会引发 SqlException。
如果您没有在 SQL 服务器之间设置镜像,则可以使用 .net 来实现。只是在一个 catch 语句中。
下面的代码..
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