永发信息网

C#中怎么获取Select count(*) 的返回值?

答案:6  悬赏:70  手机版
解决时间 2021-04-29 06:13
  • 提问者网友:玫瑰园
  • 2021-04-28 23:08
SqlConnection Conn = new SqlConnection(DataEnter.strConn); Conn.Open(); SqlCommand Cmd = new SqlCommand("select count(*) as number from Admin", Conn); SqlDataReader Dr = Cmd.ExecuteReader(); lblSum.Text = Dr["number"].ToString(); Conn.Close(); 执行的时候抛出异常 InvalidOperationException 在没有任何数据时进行无效的读取尝试。 有人知道这个问题怎么解决吗?

用户代码未处理 System.InvalidOperationException
  Message="在没有任何数据时进行无效的读取尝试。"
  Source="System.Data"


  StackTrace:
       在 System.Data.SqlClient.SqlDataReader.GetValue(Int32 i)
       在 System.Data.SqlClient.SqlDataReader.get_Item(String name)
       在 Admin_User.Page_Load(Object sender, EventArgs e) 位置 e:\fsMuseum\Admin\User.aspx.cs:行号 41
       在 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
       在 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
       在 System.Web.UI.Control.OnLoad(EventArgs e)
       在 System.Web.UI.Control.LoadRecursive()
       在 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

最佳答案
  • 五星知识达人网友:詩光轨車
  • 2021-04-29 00:05

SqlConnection Conn = new SqlConnection(DataEnter.strConn);


    Conn.Open();


    SqlCommand Cmd = new SqlCommand("select count(*) as number from Admin", Conn);
string a = Cmd.ExecuteScalar().ToString();    //Command对象的ExecuteScalar方法,返回查询结果的首行首列

全部回答
  • 1楼网友:人间朝暮
  • 2021-04-29 04:40
直接用ExecuteScalar()返回查询的首行首列就行了
  • 2楼网友:纵马山川剑自提
  • 2021-04-29 03:37

if(Dr.read())

{

lblSum.Text = Dr["number"].ToString();

}

  • 3楼网友:三千妖杀
  • 2021-04-29 03:19

lblSum.Text = Dr["number"].ToString();

换成

if(Dr.read())

{

lblSum.Text = Dr["number"].ToString();

}

  • 4楼网友:鱼忧
  • 2021-04-29 02:00

SqlConnection Conn = new SqlConnection(DataEnter.strConn);

    Conn.Open();

    SqlCommand Cmd = new SqlCommand("select count(*) as number from Admin", Conn);

    SqlDataReader Dr = Cmd.ExecuteReader();

    Dr.Read();

    lblSum.Text = Dr["number"].ToString();

    Conn.Close();

  • 5楼网友:第幾種人
  • 2021-04-29 00:26
SqlDataReader 它是数据表,也就是说他是一个表格,而你 count(*)返回的是INT记录数,也就是整型 怎么可能返回的是整型呢?
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯