簡體   English   中英

使用 C# 在本地計算機上獲取默認 SQL 服務器實例

[英]Get default SQL Server Instance On Local Machine Using C#

有辦法檢查哪個實例是主/默認。

我用這個

 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);  
             }  
         }  
     }  
 } 

查找所有實例。 之后,我檢查數據庫是否存在於任何實例上。 如果不是,我想在主實例上創建它。

根據MSDN默認實例名稱是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);
            }
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM