1

我有一个 C# 4.0 控制台应用程序和一个 SQL Server 2008 数据库,并在数据库服务器上运行。

有人知道是否有办法从 C# 代码中获取数据库属性(如 "Database Read-Only" )?

我的猜测应该是,但我无法找到准确的解决方案。

提前致谢

4

1 回答 1

1

至少有两种方法可以做到这一点。一种是使用数据库元数据表,另一种是使用SQL 管理对象,在这两种情况下都有很多数据,所以你真的需要知道你想要什么。例如,这就是您获得您提到的“数据库只读”属性的方式。

对元数据使用 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);

            }

        }
    }
}
于 2012-03-07T16:11:28.270 回答