检索特定的数据库表目录服务器C# [英] Retrieve List of Tables from Specific Database on Server C#

查看:128
本文介绍了检索特定的数据库表目录服务器C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

寻找一些C#例子,可以从一个服务器上的特定数据库中检索表的名称。我已经有一个有效的连接字符串,只是在寻找增加每个表的名称转换为以后的检索和操纵名单的正确方法。

Looking for some C# examples that can retrieve the tables' names from a specific database on a server. I already have a valid connection string, just looking for the right way of adding the names of each table into List for later retrieval and manipulation.

推荐答案

System.Data.SqlClient的有你需要的东西,而不对SYS.TABLES正式查询(尽管这也正是它的使用在背景中)。使用的SqlConnection 对象的的getSchema()方法,并指定你想要的表,它会送你一个数据表对象回来一排的每个表。它发回的数据库名,表模式名,表名和表型每一行(在该列顺序)。代码是这样的:

System.Data.SqlClient has what you need without a formal query on sys.Tables (though that's what it's using in the background). Use the GetSchema() method on the SqlConnection object and designate that you want the "Tables" and it will send you a DataTable object back with a row for each table. It sends back database name, table schema name, table name, and table type in each row (in that column order). The code would look like this:

public static List<string> GetTables(string connectionString)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        DataTable schema = connection.GetSchema("Tables");
        List<string> TableNames = new List<string>();
        foreach (DataRow row in schema.Rows)
        {
            TableNames.Add(row[2].ToString());
        }
        return TableNames;
    }
}

这篇关于检索特定的数据库表目录服务器C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆