SqlCommand 查询, SqlDataReader读取,SQL 查询怎么返回一个查询记录集的个数?SqlCommand sc = new SqlCommand(sql, connection1);
SqlDataReader sdr = sc.ExecuteDataReader();

解决方案 »

  1.   


    (1)、
    string sql= "select count(*) from where ...";
    SqlCommand sc = new SqlCommand(sql, connection1);
    int count = sc.ExecuteScalar();
    //计算记录个数
    Response.Write("记录个数为:"+count);(2)、
    string sql= "select * from where ...";
    SqlCommand sc = new SqlCommand(sql, connection1);
    SqlDataReader sdr = sc.ExecuteDataReader();
    //计算记录个数
    int count = 0;
    while(sdr.Read())
    {
        count++;
    }
    Response.Write("记录个数为:"+count);
      

  2.   

    int count = sc.ExecuteScalar();
    //计算记录个数
    Response.Write("记录个数为:"+count);
    MSDN:
    SqlCommand..::.ExecuteScalar 方法  
    SqlCommand 类  示例  另请参见  发送反馈意见  
     更新:2007 年 11 月执行查询,并返回查询所返回的结果集中第一行的第一列。忽略其他列或行。 命名空间:  System.Data.SqlClient
    程序集:  System.Data(在 System.Data.dll 中)语法
    Visual Basic(声明) 
    Public Overrides Function ExecuteScalar As Object
     
    Visual Basic (用法) 
    Dim instance As SqlCommand
    Dim returnValue As ObjectreturnValue = instance.ExecuteScalar()
     
    C# 
    public override Object ExecuteScalar()
     
    Visual C++ 
    public:
    virtual Object^ ExecuteScalar() override
     
    J# 
    public Object ExecuteScalar()
     
    JScript 
    public override function ExecuteScalar() : Object
     返回值
    类型:System..::.Object结果集中第一行的第一列;如果结果集为空,则为空引用(在 Visual Basic 中为 Nothing)。 
      

  3.   

    返回第一行第一列的值,所以你的SQL要用到Count()函数啊。
    即使你的结果集是空,返回的是空引用,这个需要你自己手工处理一下