OLE DB取得数据库的架构信息

王朝other·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

关于如何取得数据库架构信息,对于取得SQL Server和Oracal的数据库结构可能比较简单,方法也比较多。

这里整理了一个对于所有能用ADO.Net链接的数据库(比如Access,db4格式的dbf自由表等)都通用的方法

1、首先就是链接各种数据库的链接字符串,都是用ADO.Net,命名空间是:using System.Data.OleDb;

用几种数据库举个例子,需要其他的数据库链接可以到这里查:http://www.connectionstrings.com/

但要是OLE DB, OleDbConnection (.NET) 的链接方式。

Sql Server数据库连接字符串

string sConnStr = "Provider=sqloledb;Data Source=Aron1;Initial Catalog=pubs;User Id=sa;Password=asdasd;" ;

Access数据库连接字符串

string sConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\somepath\\mydb.mdb;User Id=admin;Password=;";

Dbf表(DB4格式)连接字符串

string sConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\folder;Extended Properties=dBASE IV;User ID=Admin;Password=" ;

FoxPro数据库连接字符串

string sConnStr = "Provider=vfpoledb.1;Data Source=C:\\MyDataDirectory\\;Collating Sequence=general" ;

Excel文件连接字符串

string sConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\MyExcel.xls;Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1""";

Udl文件连接字符串

string sConnStr = "File Name=c:\\myDataLink.udl;" ;

2、取得数据库架构信息,这里我以取得数据库的表格列表为例,代码如下

/// <summary>

/// 取得一个数据库的表格列表,对所有用OleDb连接的数据库都可使用

/// </summary>

/// <param name="sConnStr">数据库连接字符串</param>

/// <returns>表格列表数组</returns>

public string[] GetTabList( string sConnStr )

{

if( sConnStr == null ) throw new ArgumentNullException( "sConnStr" );

string[] sTBList;

using( OleDbConnection conn = new OleDbConnection( sConnStr ) )

{

conn.Open();

DataTable dt = conn.GetOleDbSchemaTable( OleDbSchemaGuid.Tables,

new object[] {null, null, null, "TABLE"});

conn.Close();

if ( dt.Rows.Count > 0 )

{

sTBList = new string[dt.Rows.Count];

int i = 0;

foreach ( DataRow dr in dt.Rows )

{

sTBList[i] = dr["TABLE_NAME"].ToString();

i += 1;

}

}

else

{

sTBList = new string[1];

sTBList[0] = "<没有表格>";

}

}

return sTBList;

}

其中

DataTable dt = conn.GetOleDbSchemaTable( OleDbSchemaGuid.Tables,

new object[] {null, null, null, "TABLE"});

这一句是关键,是使用 OleDbConnection 对象的 GetOleDbSchemaTable 方法展示架构信息

GetOleDbSchemaTable 返回填充了架构信息的 DataTable。

你可以让这个DataTable直接显示出来,就是详细的信息了。

如果你需要查数据库架构的其他信息时,

比如数据源、表和视图得到的目录以及所存在的约束等。表中的架构信息包括主键、列和自动编号字段。

只需要改变GetOleDbSchemaTable的参数设置,具体参数可查看

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemdataoledboledbschemaguidmemberstopic.asp

3、调用GetTabList( sConnStr )就能返回那个数据库的中表格列表

sConnStr 连接的是那种数据库,只要是ADO.Net支持的就能返回结果。

当连接的是Udl文件的时候,想通过Udl文件再连接到其他数据库时,选用的驱动一定也要是OleDB。

参考:

OleDbSchemaGuid 成员

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemdataoledboledbschemaguidmemberstopic.asp

HOW TO:使用 GetOleDbSchemaTable 和 Visual C# .NET 检索架构信息

http://support.microsoft.com/default.aspx?scid=kb;zh-cn;309681#3

ConnectionStrings

http://www.connectionstrings.com/

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航