1

我已經在數據庫服務器上啓動並運行了C#4.0控制檯應用程序和SQL Server 2008數據庫。如何從C#代碼獲取SQL Server數據庫屬性?

有人知道是否有辦法從C#代碼中獲取數據庫屬性(如「數據庫只讀」)?

我的猜測是應該的,但我無法找到準確的解決方案。

在此先感謝

回答

1

至少有兩種方法可以做到這一點。一種是在另一種情況下使用Database Metadata tables另一種使用SQL Management objects這裏有很多數據,所以你真的需要知道你想要什麼。例如,您將如何獲得您所提及的「數據庫只讀」屬性。

使用一個SqlCommand對元數據

using (SqlConnection cnn = new SqlConnection("Data Source=.;Initial Catalog=master;Integrated Security=SSPI;")) 
{ 
    SqlCommand cmd = new SqlCommand("SELECT is_read_only FROM sys.filegroups",cnn); 
    cnn.Open(); 
    var isReadOnly = cmd.ExecuteScalar(); 
    Console.WriteLine(isReadOnly); 
} 

使用SMO

using System; 
using Microsoft.SqlServer.Management.Smo; 

namespace SMO_Test 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Server srv = new Server(); //Connection to the local SQL Server 

      Database db = srv.Databases["master"]; 
      foreach (FileGroup fg in db.FileGroups) 
      { 
       Console.WriteLine(fg.ReadOnly); 

      } 

     } 
    } 
} 
+0

我最後使用的元數據的方法,但改變的SqlCommand行: 「的SqlCommand CMD =新的SqlCommand(」 SELECT DATABASEPROPERTYEX('DatabaseNameHere','Updateability')「,myConnection);」它完美的工作。感謝您的貢獻。 – G21 2012-03-07 19:13:35

相關問題