C# 使用C获取本地计算机上的默认SQL Server实例#
有一种方法可以检查哪个实例是Main/Default 我用这个C# 使用C获取本地计算机上的默认SQL Server实例#,c#,sql-server,instance,C#,Sql Server,Instance,有一种方法可以检查哪个实例是Main/Default 我用这个 private void GetDataSources2() { string ServerName = Environment.MachineName; RegistryView registryView = Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32;
private void GetDataSources2()
{
string ServerName = Environment.MachineName;
RegistryView registryView = Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32;
using (RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, registryView))
{
RegistryKey instanceKey = hklm.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL", false);
if (instanceKey != null)
{
foreach (var instanceName in instanceKey.GetValueNames())
{
Console.WriteLine(ServerName + "\\" + instanceName);
}
}
}
}
查找所有实例。之后,我检查数据库是否存在于任何实例上。如果没有,我想在主实例上创建它。根据默认的维护名称是MSSQLSERVER
:
默认实例名称为MSSQLSERVER;它不需要客户端指定实例的名称来建立连接
因此,要定义实例是否为默认实例,必须检查实例的名称是否为MSSQLSERVER
以下是可以对代码进行的更改,以定义实例是否为默认实例:
private void GetDataSources2()
{
string ServerName = Environment.MachineName;
RegistryView registryView = Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32;
using (RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, registryView))
{
RegistryKey instanceKey = hklm.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL", false);
if (instanceKey != null)
{
foreach (var instanceName in instanceKey.GetValueNames())
{
if (instanceName == "MSSQLSERVER")
// To reference default instance we should use name "ServerName".
Console.WriteLine(ServerName);
else
// To reference non default instances we should use name "ServerName\InstanceName".
Console.WriteLine(ServerName + "\\" + instanceName);
}
}
}
}
什么是“主”SQL实例?它是实例的名称吗?或者你使用单词“Main”是指默认实例吗?是的,我添加了Main,意思是默认,但有人可以更改这个名称。或者,您可以通过本地主机本身连接到默认主机并进行检查。但我不知道这是否是一个好的解决方案。根据文档
MSSQLSERVER
是保留关键字。如果实例的名称为MSSQLSERVER
,则此实例是默认的,要连接到它,可以使用名称“ServerName”或“localhost”。所以,您可以依赖此名称来定义实例是否为默认值。如果重命名实例MSSQLSERVER
,则此实例将不是默认实例,要连接到它,需要使用名称“ServerName\NewInstanceName”@MatRat在我看来,通过检查服务器实例的名称来检查其是否为默认服务器实例比尝试连接到localhost
然后检查连接是否成功更好。但您可以实施您建议的解决方案(连接到localhost
并检查)。我认为这个解决方案不会产生很多问题,因为默认服务器实例大部分时间都存在。如果您决定实施您的方法,您应该考虑到,如果实例不存在,则连接会因超时而失败。默认连接超时-15秒。如果您不更改它,则当默认实例不存在时,您的应用程序可以挂起15秒(如果您尝试同步连接)。感谢您的建议,我注意到localhost的名称因版本而异。但我不知道当更改名称时,它不是默认的。