[英]ADO.Net : Get table definition from SQL server tables
我正在使用C#编写一个方法,该方法返回有关表的以下信息:列名,列类型,列大小,外键。
有人能指出我如何实现这个目标吗?
这实际上取决于您与数据库的通信方式。 如果您正在使用LinqToSQL或其他类似的ORM,这将非常简单,但如果您想通过查询获取这些值,我建议您使用INFORMATION_SCHEMA视图,因为这些视图快速且容易查询。
例如
select * from information_schema.columns where table_name = 'mytable'
要获得FK和Schema,您应该能够使用:
DA.FillSchema()
DS.Table("Name").PrimaryKey
或者使用下面演示的方法调用sp_fkey
来自 AND Another Link的代码片段
private void LoanSchema()
{
private List<String> tablesList = new List<String>();
private Dictionary<String, String> columnsDictionary = new Dictionary<String, String>();
string connectionString = "Integrated Security=SSPI;" +
"Persist Security Info = False;Initial Catalog=Northwind;" +
"Data Source = localhost";
SqlConnection connection = new SqlConnection();
connection.ConnectionString = connectionString;
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "exec sp_tables";
command.CommandType = CommandType.Text;
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
tablesList.Add(reader["TABLE_NAME"].ToString());
}
reader.Close();
command.CommandText = "exec sp_columns @table_name = '" +
tablesList[0] + "'";
command.CommandType = CommandType.Text;
reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
columnsDictionary.Add(reader["COLUMN_NAME"].ToString(), reader["TYPE_NAME"].ToString());
}
}
如果您正在使用MS SQL Server,那么您应该明确地查看SMO命名空间(服务器管理对象)。
有些对象可以在.net中使用,负责数据库中的各种事物(包括但不限于表,列,约束等)
您可以使用SqlDataAdapter.FillSchema()方法。
或者,您可以在将SqlDataAdapter的MissingSchemaAction属性设置为AddWithKey之后使用SqlDataAdapter.Fill()方法。 但是,如果您只需要架构,则必须确保查询不返回任何行。 这可以通过在查询中添加WHERE 1 = 2等语句来实现。
我认为你需要System.Data.DataTable类:
http://msdn.microsoft.com/en-us/library/system.data.datatable.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.