从查询中创建 DataTable 的最快方法是什么?

5
这个SQL查询需要哪些代码才能使用最少的行数生成一个DataTable呢?
SELECT * 
FROM [Table1] 
WHERE ([Date] BETWEEN @Date1 AND @Date2) AND 
      ([Field1] IS NULL OR [Field2] IS NULL)

2
你已经得到了很好的答案,请接受其中一个。 - nawfal
3个回答

16

使用SqlDataAdapter填充一个DataTable。

DataTable dt = new DataTable();
using (SqlConnection yourConnection = new SqlConnection("connectionstring"))
{
    using (SqlCommand cmd = new SqlCommand("....your sql statement", yourConnection))
    {
        using (SqlDataAdapter da = new SqlDataAdapter(cmd))
        {
            da.Fill(dt);
        }
    }
}

使用 using 块与您的 SqlConnection, SqlCommand, 和 SqlDataAdapter 一起使用,因为它们实现了 IDisposable 接口。此外,使用参数化查询


你不想在SqlCommand和SqlDataAdapter中也包含“using”语句吗?因为它们也实现了IDisposable接口。 - NightShovel
@NightShovel,没错。我应该使用using块。 - Habib

3

试试这个

SqlCommand command = new SqlCommand(query, conn);
DataTable dt = new DataTable();
using(SqlDataReader reader = command.ExecuteReader())
{
     dt.Load(reader);
}

1
我会说这就是答案 :) - nawfal
1
-1,如果需要填充数据集,则DataReader不适用。它在需要在读取数据时利用数据的情况下非常有用。 - Asif Mushtaq

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接