在 C# 中获取数据库 Table

Get Database Table in C#

我正在尝试根据 ObjectType 获取数据库表,我该如何实现? 到目前为止我试过这个方法

 public void  GetTableByObjectType(string ObjectType) {
         SqlConnection conn = new SqlConnection(
          "Data Source=Local;Initial Catalog=myConnection;User ID=sa;Password=12345");
          DataTable t = conn.GetSchema("Objectype");

此代码将帮助您从您尝试访问的数据库中获取所有表

string SQLExpression = "SELECT * FROM SYS.Tables Order By Name";

SqlConnection conn = new SqlConnection(
              "Data Source=Local;Initial Catalog=myConnection;User ID=sa;Password=12345");

SqlDataAdapter adp = new SqlDataAdapter(SQLExpression, cn);

DataSet ds = new DataSet();

adp.Fill(ds, "SystemData");

在此示例中,您将获得数据库表的架构:

String ObjectType = "Tables"; //collectionName argument to get Tables

String[] tableRestrictions = new String[4];
tableRestrictions[2] = "TableYouWant"; //name of the table whose get the schema
DataTable courseTableSchemaTable = conn.GetSchema(ObjectType, tableRestrictions);

您可以对 Table 集合使用四个限制,因此您应该创建一个包含 4 个成员的数组。 对于数组 tableRestrictions

  • 0-member代表目录;
  • 1-member代表Schema;
  • 2人代表Table姓名;
  • 3-member表示Table类型。

另请参阅:https://msdn.microsoft.com/it-it/library/ms136366(v=vs.110).aspx