使用DataReader的GetSchemaTable()方法可以获得数据表中包含的结构信息,此方法返回一个DataTable,DataTable中的每一行(Row)的ColumnName属性值即为数据表的一个字段名。
SqlConnection coreDB=new SqlConnection();
coreDB.ConnectionString= "workstation id="GQA-ERIC-LV";packet size=4096;integrated security=SSPI;" +
"data source="gqa-eric-lv";persist security info=False;initial catalog=CoreDB";
string mySelectQuery = "SELECT ID, Title FROM myBBS order by id asc";
SqlCommand myCommand = new SqlCommand(mySelectQuery,coreDB);
coreDB.Open();
SqlDataReader myReader=myCommand.ExecuteReader();
//将数据库定义的信息保存到表SchemaTable中:
DataTable SchemaTable=myReader.GetSchemaTable();
//表SchemaTable的每一行表示数据库表一个字段的信息:
Response.Write("
");
foreach(DataRow myRow in SchemaTable.Rows)
{
Response.Write(""); Response.Write(myRow["ColumnName"]); Response.Write(" | ");
}
Response.Write("
");
while(myReader.Read())
{
Response.Write("");
Response.Write(""+myReader["ID"].ToString()+" | ");
Response.Write(""+myReader["title"].ToString()+" | ");
Response.Write("
");
}
Response.Write("
");
myReader.Close();
coreDB.Close();
显示的结果如图:
以上亦例示了SqlConnection,SqlCommand,DataReader的使用。
数据库coreDB中的表myBBS定义如下:
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[myBBS]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)