广告
返回顶部
首页 > 资讯 > 后端开发 > 其他教程 >C#获取数据库中所有表名、列名的示例代码
  • 925
分享到

C#获取数据库中所有表名、列名的示例代码

2024-04-02 19:04:59 925人浏览 八月长安
摘要

C# 获取数据库中所有表名、列名,实现代码如下所示: List<Dictionary<string, string>> GetColsNam

C# 获取数据库中所有表名、列名,实现代码如下所示:

        List<Dictionary<string, string>>  GetColsName(Guid gtype,string tableName,string itemIndex= "COLUMN_NAME")
        {
            DataTable dsTablesData = DbDataHelper.GetCon().GetOleDbSchemaTable(gtype, new Object[] { null, null, tableName, null });
            List<Dictionary<string, string>> ditCol = new List<Dictionary<string, string>>() ;

            for (int i = 0; i < dsTablesData.DefaultView.Table.Rows.Count; i++)
            {
                ditCol.Add(new Dictionary<string, string> { { i.ToString(), i.ToString() } });
            }

            foreach (DataRow item in dsTablesData.DefaultView.Table.Rows)
            {
                int pos = Convert.ToInt32(item["ORDINAL_POSITION"]);
                int typeIndex = Convert.ToInt32(item["DATA_TYPE"]);

                ditCol[pos-1]= new Dictionary<string, string> { { item[itemIndex].ToString(), DBData.getInstance().GetColNameType(typeIndex) } };
            }

            return ditCol;
        }

        List<string> GetTablesName(Guid gtype,string tableType ="TABLE", string strTableName =null , string itemIndex= "TABLE_NAME")
        {
            List<string> strNames = new List<string>();

            DataTable dsTablesData = DbDataHelper.GetCon().GetOleDbSchemaTable(gtype, new Object[] { null, null, strTableName, tableType });

            foreach (DataRow item in dsTablesData.DefaultView.Table.Rows)
            {
                strNames.Add(item[itemIndex].ToString());
            }

            return strNames;
        }

调用

            DBData.getInstance()._tableNames = GetTablesName(OleDbSchemaGuid.Tables);

            foreach (var tableName in DBData.getInstance()._tableNames)
            {
                List<Dictionary<string, string>> tmp = GetColsName(OleDbSchemaGuid.Columns, tableName);
            }

通过dataTable获取

       /// <summary>
       /// 根据datatable获得列名
       /// </summary>
       /// <param name="dt">表对象</param>
       /// <returns>返回结果的数据列数组</returns>
        public static List<string> GetColumnsByDataTable(DataTable dt)
        {
            List<string> list = new List<string>();

            foreach (DataColumn item in dt.Columns)
            {
                list.Add(item.ColumnName);
            }

            return list;
        } 

到此这篇关于C# 获取数据库中所有表名、列名的文章就介绍到这了,更多相关C# 获取数据库表名、列名内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: C#获取数据库中所有表名、列名的示例代码

本文链接: https://www.lsjlt.com/news/150364.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作