1)
While the SqlDataReader is being used, the associated SqlConnection is busy serving the SqlDataReader, and no other operations can be performed on the SqlConnection other than closing it. This is the case until the Close method of the SqlDataReader is called. For example, you cannot retrieve output parameters until after you call Close.
如果上述说法正确,那么为什么以下方法能够在阅读器关闭之前从输出参数中检索值:
public int Something()
{
using (SqlConnection con = new SqlConnection(this.ConnectionString))
{
SqlCommand cmd = new SqlCommand("some_procedure", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@ID", SqlDbType.Int).Direction = ParameterDirection.Output;
con.Open();
cmd.ExecuteReader();
return (int)cmd.Parameters["@ID"].Value;
}
}
2)
You can reset the CommandText property and reuse the SqlCommand object. However, you must close the SqlDataReader before you can execute a new or previous command.
为什么在执行新命令之前必须关闭sqldatareader?
谢谢
最佳答案
在第一个问题中,您正在执行 NonQuery - 因此在获取输出参数之前没有需要关闭的阅读器。
对于第二个问题,你就做吧。当一个阅读器打开时,该命令不会让您调用另一阅读器。
关于.net - 如果在 SqlDataReader 关闭之前我们无法检索输出参数,那么为什么......?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2632619/