如何解决如何使用“使用”语句处理数据表
我试图对数据表使用using语句,以便在超出范围时进行处理,但是在using范围内,它不能将datatable分配给using变量。下面是代码。 无需使用“使用语句”和使用DataTable dt = null,一切正常。
using (DataTable dt = new DataTble())
{
using (SqlConnection connection = new SqlConnection("DBConection"))
{
cmd = new SqlCommand("SPNAME",connection);
cmd.CommandType = CommandType.StoredProcedure;
dt = (DataTable)cmd.ExecuteNonquery(); // here it says cannot assign to dt because it is a using variable
}
return dt;
}
解决方法
您应该记住,在using块中,对象是只读的,不能修改或重新分配。 https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement
,发布的用于填充DataTable
的代码对我来说似乎是错误的,因为ExecuteNonQuery()
返回了int
,因此无论如何都不能将其强制转换为DataTable
。>
我的方法是使用SqlDataAdapter
来填充表格。
这里的代码可以编译-但是 不要使用它,因为这将无法工作 :
public DataTable UsingDataTable()
{
using (SqlConnection connection = new SqlConnection("DBConection"))
{
using (SqlCommand cmd = new SqlCommand("SPNAME",connection))
{
cmd.CommandType = CommandType.StoredProcedure;
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
da.Fill(dt);
return dt;
}
}
}
}
}
您不能同时返回要处置的DataTable
。调用代码必须能够在 处理之前使用它。
因此,方法是将使用DataTable
的代码 注入 到该方法中,以便可以在返回之前执行该代码。试试这个:
public void UsingDataTable(Action<DataTable> action)
{
using (SqlConnection connection = new SqlConnection("DBConection"))
{
using (SqlCommand cmd = new SqlCommand("SPNAME",connection))
{
cmd.CommandType = CommandType.StoredProcedure;
using (SqlDataAdapter a = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
a.Fill(dt);
action(dt);
}
}
}
}
}
现在您可以这样称呼:
UsingDataTable(dt => Console.WriteLine(dt.Rows[0][0].ToString()));
,
不需要在数据表,数据集上实现using语句。这是因为数据表,数据集会抑制其构造函数中的最终确定。在数据表,数据集上使用using语句并没有真正的好处。
,正如评论所说,您只能在实现using
的{{1}}上使用class
语句,而IDisposible
则不能。但是,您可以使用自己的Datatable
方法来处置DataTable
。只是要使其非常清楚,这也是没有必要的,因为dispose()
没有任何不受管理的资源。
有关详细信息,请查看this答案。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。