C# 如何查看数据库结构
时间: 2023-08-10 18:40:42 浏览: 49
在 C# 中,可以使用 System.Data.SqlClient 命名空间中的 SqlConnection、SqlCommand 和 SqlDataReader 类来查看数据库结构。以下是一个简单示例:
```
using System;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = "Data Source=(local);Initial Catalog=MyDatabase;Integrated Security=True";
SqlConnection connection = new SqlConnection(connectionString);
try
{
connection.Open();
// 获取数据库中所有表的信息
SqlCommand command = new SqlCommand("SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS", connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string tableName = reader.GetString(0);
string columnName = reader.GetString(1);
string dataType = reader.GetString(2);
Console.WriteLine($"Table: {tableName}, Column: {columnName}, Data Type: {dataType}");
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
connection.Close();
}
}
}
```
上面的示例中,我们使用了 INFORMATION_SCHEMA.COLUMNS 表来获取数据库中所有表的信息,包括表名、列名和数据类型。可以根据实际需求修改 SQL 查询语句。