简体   繁体   English

从SQL Server到DataTable C#检索列名和类型

[英]Retrieve column names and types from SQL Server to DataTable C#

What would be the best way of building an empty DataTable based on existing table in SQL server? 在SQL Server中基于现有表构建空DataTable的最佳方法是什么? My current try is this one, which is just retyping this manually, so it is not great, especially for large data sets. 我当前的尝试是此操作,它只是手动重新键入此操作,因此它并不是很好,特别是对于大型数据集。

private DataTable createEmptyReadingDataTableReadyToSaveToDb()
{
    dtbl.Columns.Add("ProductId", typeof(string));
    dtbl.Columns.Add("Price", typeof(float));
    dtbl.Columns.Add("Revenue", typeof(float));
    dtbl.Columns.Add("URL", typeof(string));
    //  etc ....
    return dtbl;
}

I read today about schemas, which seem natural for this task. 今天,我阅读了有关架构的内容,这似乎很自然。 It got me more confused than I thought this would be. 这让我比我想象的更加困惑。 Anyways such approach below returns a datatable returning broad set of information about the dataset, but I do not find there accessors to get information about the interesting DataTable (below). 无论如何,下面的这种方法都会返回一个数据表,该数据表返回有关数据集的广泛信息集,但是我找不到那里的访问器来获取有关有趣的数据表的信息(如下)。 Probably I do something wrong. 可能我做错了。

private static DataTable getReadingTableFromSchema()
{
    using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["LocalDbConnnectionString"].ConnectionString))
    {
        string sql = "SELECT * FROM [Readings]";
        conn.Open();
        SqlCommand cmd = new SqlCommand(sql, conn);
        SqlDataReader reader = cmd.ExecuteReader();
        DataTable dtbl = reader.GetSchemaTable();
        return dtbl;
    }
}

I could also just try the approach with DataAdapter reading the data, then filling it (basically copying the DataTable) and then deleting all rows to have the table empty - but this would definitely affect the performance. 我也可以尝试使用DataAdapter读取数据,然后填充(基本上是复制DataTable)然后删除所有行以使表为空的方法,但这肯定会影响性能。 What would be the right solution? 什么是正确的解决方案?

you can use DataAdapter and fill DataTable with full schema: 您可以使用DataAdapter并用完整模式填充DataTable:

private static DataTable getReadingTableFromSchema()
{
    using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["LocalDbConnnectionString"].ConnectionString))
    {
        string sql = "SELECT * FROM [Readings]";
        conn.Open();
        SqlCommand cmd = new SqlCommand(sql, conn);
        DbDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dtbl = new DataTable();
        da.FillSchema(dtbl, SchemaType.Source);
        return dtbl;
    }
}

And, I suggest you to use "using" for command and adapter too 而且,我建议您也将“ using”用于命令和适配器

Using a bit of LINQ 使用一点LINQ

using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["LocalDbConnnectionString"].ConnectionString))
{
    conn.Open();
    using (var reader = new SqlCommand("SELECT * FROM [Readings] WHERE 1 = 0", conn).ExecuteReader())
    {
        var dataColumns = Enumerable.Range(0, reader.FieldCount)
                                    .Select(i => new DataColumn(reader.GetName(i), reader.GetFieldType(i)))
                                    .ToArray();

        var dataTable = new DataTable("Readings");
        dataTable.Columns.AddRange(dataColumns);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM