我有2个SqlCommand,其中之一嵌套。为什么它不允许我发出第二个SqlCommand(我正在使用单独的SQLCommand)?它给出错误“已经有一个与此命令关联的打开的DataReader,必须先关闭”。 。如果我使用单独的SqlConnection,那很好。不允许嵌套SQLCommand?
SqlCommand cmd = new SqlCommand(qry, cn);
SqlDataReader rd = cmd.ExecuteReader();
while (rd.Read())
{
....
try
{
SqlCommand cmd2 = new SqlCommand(qry2, cn);
cmd2.ExecuteNonQuery();
}
catch (Exception e)
{
// I get this error here
// System.Data; There is already an open DataReader associated with this Command which must be closed first.
}
}
您需要额外的连接实例才能为同时查询执行具有相同连接字符串的另一个查询。由于在执行另一个查询时可能无法停止DataReader,所以考虑将DataReader内容拉到DataTable中关闭第一个连接并在迭代DataTable内容时重新打开。 –