如题,我的sql语句可写成"select count(*) as RecNum from mytable where age = 30"
或"select count(*) from mytable where age = 30",现在不知道该如何把结果赋值给变量int n
请教!!!!!!!!!!1我已经试了好几个方法都不行,请指教!!!!!!!!!!

解决方案 »

  1.   

    int n = (int)comm.ExecuteScalar();
      

  2.   

    你sql语句里面的count(*)函数,是获得数量,是int 类型的啊。怎么会转换不了呢。。
    代码贴出来看下
      

  3.   

    下面的代码应该可行,没有编译环境,不知道有没有笔误:
    string sqlSelect = "select count(*) from mytable where age = 30";
    SqlConnection cn = new SqlConnection(strcon);
    cn.Open();
    SqlCommand cm = new SqlCommand(sqlSelect1, cn);
    SqlDataReader dr = cm.ExecuteReader();
    while (dr.Read())
    {
       int cnt = Convert.ToInt16(dr["cnt"]);
    }
    dr.Close();
    cn.Close();
      

  4.   

    楼上应该是正解,不过你的sql似乎应写成"select count(*) as cnt from mytable where age = 30"; 
    我用的是别的方法,一点点试出来的,不容易啊,跟大家分享一下:
    string sqlSelect = "select count(*) from mytable where age = 30"; 
    SqlConnection cn = new SqlConnection(strcon); 
    cn.Open(); 
    SqlCommand cm = new SqlCommand(sqlSelect, cn); 
    object obj = cm.ExecuteOracleScalar();
    int cnt = Convert.ToInt32(obj.ToString());
    cn.Close();真是耗了好些功夫,谢谢大家关注!