通过DataReader获取sql查询的字段元数据信息

原理

应用程序调用 GetSchemaTable()
    ↓
ADO.NET 驱动程序生成元数据查询SQL
    ↓
发送到数据库服务器执行
    ↓
数据库返回结果集架构信息(不包含实际数据)
    ↓
ADO.NET 解析架构信息并构建 DataTable
    ↓
返回包含完整列信息的 DataTable

sqlsugar

            var sql = $@"select * from sys_database d
left join sys_table t
on d.""id"" = t.database_id";
            //var behavior80c9dce3fe3b43b8847e55614ab45b56 = CommandBehavior.SequentialAccess |  CommandBehavior.CloseConnection;
            var behavior80c9dce3fe3b43b8847e55614ab45b56 = CommandBehavior.SchemaOnly;
            res = new List<object>();

            var result = await sqlSugar.Ado.GetCommand(
                sql, paraList.ToArray()).ExecuteReaderAsync(CommandBehavior.SchemaOnly);
            var schema = result.GetSchemaTable();
            foreach (DataRow row in schema.Rows)
            {
                string columnName = row["ColumnName"].ToString();
                Type dataType = (Type)row["DataType"];
                int columnSize = (int)row["ColumnSize"];
                //bool isNullable = (bool)row["AllowDBNull"];
                var isNullable = row["AllowDBNull"];
                // 还有其他信息,如精度、小数位数等
                Console.WriteLine($"列名: {columnName}, 类型: {dataType}, 大小: {columnSize}, 可空: {isNullable}");
            }

ado

using (SqlCommand command = new SqlCommand("SELECT TOP 0 * FROM employees", connection))
{
    using (SqlDataReader reader = command.ExecuteReader())
    {
        // 获取数据表的Schema
        var schemaTable = reader.GetSchemaTable();

        // 遍历每一列的Schema信息
        foreach (DataRow row in schemaTable.Rows)
        {
            string columnName = (string)row["ColumnName"];
            Type dataType = (Type)row["DataType"];
            int maxLength = (int)row["ColumnSize"];
            bool allowNull = (bool)row["AllowDBNull"];

            // 输出列的信息
            Console.WriteLine("列名:{columnName}");
            Console.WriteLine("数据类型:{dataType}");
            Console.WriteLine("最大长度:{maxLength}");
            Console.WriteLine("是否允许为空:{allowNull}");
            Console.WriteLine("---------------------------------------");
        }
    }
}

posted @ 2025-11-21 22:06  Hey,Coder!  阅读(4)  评论(0)    收藏  举报