日期:2014-05-18  浏览次数:20868 次

关于SqlDataReader的IndexOutOfRangeException问题
我是个渣学生,我希望能把StorageRec表中某一条件下(WeapName=XXX)的列StoCount做求和计算后返回一个int值,用作以后的计算 
以下是我的代码:

C# code

        public static int Count(Entity.WeaponInfo Count)
        {
            SqlConnection conn = new SqlConnection("Server=.; Integrated Security=True; Database=WeaponSalesMng");
            SqlCommand cmd = new SqlCommand("select sum(StoCount) from StorageRec where WeapName=@WeapName", conn);
            cmd.Parameters.Add(new SqlParameter("@WeapName", Count.Name));
            conn.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            dr.Read();
            int count = (int)dr["StoCount"];//未处理 IndexOutOfRangeException
            return count;
        }



求解。。。。。。


------解决方案--------------------
cmd.ExecuteScalar();
返回结果集的第一行第一列,直接用这个就可以了
------解决方案--------------------
SqlCommand cmd = new SqlCommand("select sum(StoCount) as StoCount from StorageRec where WeapName=@WeapName", conn);
cmd.Parameters.Add(new SqlParameter("@WeapName", Count.Name));
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
int count = (int)dr["StoCount"];
}

------解决方案--------------------
这样查询,列名就变成了 sum(StoCount) 而不再是 StoCount
(int)dr[0] 按索引查找,或
(int)cmd.ExecuteReader() 返回第一行第一列的值