现在的位置: 首页 > 综合 > 正文

C# 获取数据库表信息,列信息

2018年04月18日 ⁄ 综合 ⁄ 共 2015字 ⁄ 字号 评论关闭

conn.Open();
string[] restrictions = new string[4];
restrictions[3] = “BASE TABLE";      
DataTable table = conn.GetSchema("Tables", restrictions);     
conn.Close();

获取表的信息:

conn.Open();
string[] restrictions = new string[4];
restrictions[1] = "dbo";      
DataTable table = conn.GetSchema("Tables", restrictions);     
conn.Close();

返回的table是表的所有信息,而不仅仅是名字,可以通过如下语句查看这些信息:

foreach (System.Data.DataRow row in table.Rows)
{
foreach (System.Data.DataColumn col in table.Columns)
     {
         Console.WriteLine("{0} = {1}", col.ColumnName, row[col]);
     }
}

要获取指定表的信息,关键是要设置数组restrictions的值。对于表而言,这个数组有如下的含义:

Restriction[0]表示表所在的Catalog

Restriction[1]表示表的所有者

Restriction[2]表示表的名字

Restriction[3]表示表的类型:

上面的例子就获取了所有dbo拥有的表的信息。如果要获取所有的用户表,而非系统表,可用如下语句:

 

获取列的信息:

conn.Open();
string[] restrictions = new string[4];
restrictions[1] = "dbo";      
DataTable table = conn.GetSchema("Columns", restrictions);     
conn.Close();

与获取表的代码很类似,只是GetSchema的第一个参数不同。同样,返回结果取决于restriction的值。此时,

Restriction[0]表示列所在的Catalog

Restriction[1]表示列的所有者

Restriction[2]表示列所在的表的名字

Restriction[3]表示列名

例如:

// restriction string array
string[] res = new string[4];
 
// dbo拥有的所有表的所有列的信息
res[1] = "dbo";
DataTable t1 = conn.GetSchema("Columns", res);
 
// 任意owner/schema所拥有的一个叫authors的表的列信息
res[2] = "authors";
DataTable t2 = conn.GetSchema("Columns", res);
 
//任意owner/schema所拥有的一个叫authors的表的列name的信息
res[2] = "authors";  res[3] = "name ";
DataTable t3 = conn.GetSchema("Columns", res);
 
//任意owner/schema任意表中的一个列名是name的列的信息。
res[3] = "name";
DataTable t4 = conn.GetSchema("Columns", res);

 

 

获取数据库的其它信息都可以使用GetSchema,只是第一个参数不同。这个参数在不同的数据库有差异:

1、在SQL Server中,可以获取的架构集合如下:

·     Databases

·     ForeignKeys

·     Indexes

·     IndexColumns

·     Procedures

·     ProcedureParameters

·     Tables

·     Columns

·     Users

·     Views

·     ViewColumns

·     UserDefinedTypes

2、在Oracle中,可以获取的架构集合如下:

·     Columns

·     Indexes

·     IndexColumns

·     Procedures

·     Sequences

·     Synonyms

·     Tables

·     Users

·     Views

·     Functions

·     Packages

·     PackageBodies

·     Arguments

·     UniqueKeys

·     PrimaryKeys

·     ForeignKeys

·     ForeignKeyColumns

·     ProcedureParameters

原文地址:http://www.csharpwin.com/csharpspace/11457r2196.shtml 
   转载请注明出处

抱歉!评论已关闭.