ADO.Net:从SQL Server表获取表定义

6
我正在使用C#编写一个方法,返回表格的以下信息:列名、列类型、列大小、外键。
有人能指导我如何完成这个任务吗?
5个回答

9
这实际上取决于您与数据库的通信方式。如果您正在使用LinqToSQL或其他类似的ORM,则这将非常容易,但如果您想通过查询获取这些值,我建议您使用INFORMATION_SCHEMA视图,因为它们快速且易于查询。

例如:

select * from information_schema.columns where table_name = 'mytable'

这太棒了。它替代了我原本需要两页查询的工作。 - rediVider

5
要获取外键和模式(Schema),你可以使用以下代码:
DA.FillSchema() 

DS.Table("Name").PrimaryKey 

通过以下所示的方法调用sp_fkey

代码片段来自AND 另一个链接

    private void LoanSchema()
    {

         private List<String> tablesList = new List<String>();
         private Dictionary<String, String> columnsDictionary = new Dictionary<String, String>();

          string connectionString = "Integrated Security=SSPI;" +
          "Persist Security Info = False;Initial Catalog=Northwind;" +
          "Data Source = localhost";
          SqlConnection connection = new SqlConnection();
          connection.ConnectionString = connectionString;
          connection.Open();

          SqlCommand command = new SqlCommand();
          command.Connection = connection;
          command.CommandText = "exec sp_tables";
          command.CommandType = CommandType.Text;

          SqlDataReader reader = command.ExecuteReader();

           if (reader.HasRows)
           {
               while (reader.Read())
                  tablesList.Add(reader["TABLE_NAME"].ToString());
           }
           reader.Close();

           command.CommandText = "exec sp_columns @table_name = '" +
           tablesList[0] + "'";
           command.CommandType = CommandType.Text;
           reader = command.ExecuteReader();

            if (reader.HasRows)
            {
                while (reader.Read())
                          columnsDictionary.Add(reader["COLUMN_NAME"].ToString(), reader["TYPE_NAME"].ToString());
             }
}

1

如果您正在使用 MS SQL Server,则一定要查看 SMO 命名空间(服务器管理对象)。

有一些对象可以在 .net 中使用,负责数据库中的各种事物(包括但不限于表、列、约束等)。


1
你可以使用SqlDataAdapter.FillSchema()方法。或者,在将SqlDataAdapter的MissingSchemaAction属性设置为AddWithKey之后,可以使用SqlDataAdapter.Fill()方法。但是,如果你只想要架构,你必须确保你的查询不返回任何行。这可以通过向查询添加类似WHERE 1=2的语句来实现。

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接