我想在题目中的sql语句执行完之后,取出count值,赋给一个整型变量,然后再确定后面的操作。请问怎么把它赋给一个int变量????
我采用的方法是:
string str="select count(*) from table";
int countNum =Dboperate.exeCommand(str);
注:Dboperate是我自己写的一个执行sql语句的类。
请大家帮帮忙。谢谢。

解决方案 »

  1.   

    int num;
            string str = "select count(*) from table";
            SqlCommand sComm = new SqlCommand(str,conn_string);
            num = (int)sComm.ExecuteScalar();
      

  2.   

    int num;
            string str = "select count(*) from table";
            SqlCommand sComm = new SqlCommand(str,conn_string);
            num = Convert.ToInt32(sComm.ExecuteScalar());
      

  3.   

    ????可以这样写:SqlCnn表示连接:string str="select count(*) from table";OleDbDataAdapter OleAdp = new OleDbDataAdapter (str,SqlCnn);
    DataSet DSet = new DataSet();OleAdp.fill(DSet);foreach(DataRow DRow in DSet.Table[0].Rows)
    {
      countNum =Convert.ToInt32(DRow.ItemArray[0].ToString);
    }这样写,因为查询结果就只有一条;可以这样获取你要的东东!~~
      

  4.   

    谢谢大家,但是现在又出现了一个问题:
    我的代码是:
    1. string str="select count(*) from table";
    2. cmd =new sqlCommand(str,connectionString);
    3. num=convert.toint32(cmd.executescalar());
    问题是我的表中一条数据都没有,为什么单步调试的时候,num显示为1呢?再次感谢。
      

  5.   

    num = 0; string str="select count(*) from table"; 
     cmd =new sqlCommand(str,connectionString);
     SqlDataReader reader = cmd.ExecuteReader();
     
     if(!reader.Equals(null))
     {
       if(reader.HasRows)
         num = reader.GetDecimal(0);
     }
     
      

  6.   

    public static object ExecuteScalar(SqlParameter[] Parms, string SqlText, CommandType CmdType)
    {
    using (SqlConnection Conn = new SqlConnection(strConn))
    {
    SqlCommand Cmd = new SqlCommand();
    PrepareCommand(Conn, Parms, SqlText, Cmd, CmdType);
    object obj = Cmd.ExecuteScalar();
    Cmd.Parameters.Clear();
    Cmd.Dispose();
    if((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
    {
    return null;
    }
    else
    {
    return obj;
    }
    }
    }调用这个方法,再进行强类型转换