从查询结果中获取所有行
本文关键字:获取 查询 结果 | 更新日期: 2023-09-27 18:28:07
我有一个返回布尔值的存储过程。(0或1)。它返回多行。我的问题是如何遍历所有结果。
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBReader"].ConnectionString))
{
using (SqlCommand com = new SqlCommand("Reader.usp_CheckerIsStopped", con))
{
com.CommandType = CommandType.StoredProcedure;
com.Parameters.Add("@fld_UserID", SqlDbType.Int).Value = this.UserID;
con.Open();
SqlDataReader dr = com.ExecuteReader();
if (dr.Read() == 1)
{
return true;
}
else
{
return false;
}
}
}
它在dr.Read() == 1
中有错误
错误:
运算符==不能应用于类型bool to int"
我的存储过程返回包含0或1的多行,我想获得这些值,因为我想检查它是否等于false(0或1)的true
if (e.Row.RowType == DataControlRowType.DataRow)
{
//if (e.Row.Cells[11].Text == "In Progress")
//{
// System.Web.UI.WebControls.ImageButton StartImageButton = (System.Web.UI.WebControls.ImageButton)e.Row.Cells[1].FindControl("StartImageButton");
// StartImageButton.Visible = false;
//}
gvfunct.UserID = Convert.ToInt32(Session["UserID"]);
gvfunct.CheckIsStopped();
if (gvfunct.CheckIsStopped() == true)
{
System.Web.UI.WebControls.ImageButton StartImageButton = (System.Web.UI.WebControls.ImageButton)e.Row.Cells[2].FindControl("StartImageButton");
StartImageButton.Visible = true;
System.Web.UI.WebControls.ImageButton StopImageButton = (System.Web.UI.WebControls.ImageButton)e.Row.Cells[1].FindControl("StopImageButton");
StopImageButton.Visible = false;
}
else
{
System.Web.UI.WebControls.ImageButton StopImageButton = (System.Web.UI.WebControls.ImageButton)e.Row.Cells[1].FindControl("StopImageButton");
StopImageButton.Visible = true;
System.Web.UI.WebControls.ImageButton StartImageButton = (System.Web.UI.WebControls.ImageButton)e.Row.Cells[2].FindControl("StartImageButton");
StartImageButton.Visible = false;
}
}
您需要继续Read()
并对这些结果做一些处理。
while (dr.Read())
{
}
您可以看到,Read()
方法返回一个bool
。所以,现在如果你想得到每一行的结果,你可以这样做:
while (dr.Read())
{
var val = dr.GetInt32(0);
}
这将从Read()
中当前所在的行中获取第一列的值,并将其强制转换为int
。当然,如果您尝试强制转换string
或其他内容,那么这一行可能会引发错误。假设DataReader
是只读的、仅向前的数据缓冲区。实际上,它一次只从服务器中提取一行数据,从而在Read()
操作期间保持连接打开,直到它超出范围。
由于dr.Read()
返回bool
,因此与int
比较时出错
如果SqlDataReader的行为false,则返回true。
所以把你的代码改为
return dr.Read();
而不是
if (dr.Read() == 1)
{
return true;
}
else
{
return false;
}
更换
if (dr.Read() == 1)
{
return true;
}
带有
if (dr.Read())
{
return true;
}
您需要显式强制转换它,或者只使用它的正确布尔类型因此,您可以使用if (dr.Read() == true)
或if (dr.Read())
而不是if (dr.Read() == 1)
据我所知,没有直接转换,例如(bool)1
不起作用,但您可能总是使用Convert.ToBoolean(1)
或其他一些方法将其转换为
您也可以创建自己的自定义铸造方法
IntToBool (int bool)
{
if(bool == 1) return true;
return false;
}
目前还不清楚存储过程返回的内容,但如果第一行和第一列包含一个整数,则可能会忘记读取器,并使用SqlCommands ExecuteScalar方法,如下所示:
return com.ExecuteScalar() == 1;
如果您需要遍历所有行,请尝试此
if(dr.Read()){
if(dr.Read()) return true;
else return false;
}
else return false;
这将读取dr两次,如果找到2行,则返回true。如果找到0或1行,则为False。