您可以使用GetSchema ADO函數獲取具有幾乎所有模式數據的DataTable。
本例使用的SQLConnection,但功能可以以任何ODBCConnection.
using System;
using System.Data;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = GetConnectionString();
sing (SqlConnection connection = new SqlConnection(connectionString))
{
// Connect to the database then retrieve the schema information.
connection.Open();
DataTable table = connection.GetSchema("Tables");
// Display the contents of the table.
DisplayData(table);
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}
}
private static string GetConnectionString()
{
// To avoid storing the connection string in your code,
// you can retrieve it from a configuration file.
return "Data Source=(local);Database=AdventureWorks;" +
"Integrated Security=true;";
}
private static void DisplayData(System.Data.DataTable 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]);
}
Console.WriteLine("============================");
}
}
}
還有更好的方法:使用'SQL'目錄視圖,在SQL Server 2005中引入而不是棄用的'sysobjects' - 您的查詢將是:'SELECT Name FROM sys.tables' – 2011-02-24 17:31:52