select count(*) from table where....
我想在题目中的sql语句执行完之后,取出count值,赋给一个整型变量,然后再确定后面的操作。请问怎么把它赋给一个int变量????
我采用的方法是:
string str= "select count(*) from table ";
int countNum =Dboperate.exeCommand(str);
注:Dboperate是我自己写的一个执行sql语句的类。
请大家帮帮忙。谢谢。
------解决方案--------------------int num;
string str = "select count(*) from table ";
SqlCommand sComm = new SqlCommand(str,conn_string);
num = (int)sComm.ExecuteScalar();
------解决方案--------------------int num;
string str = "select count(*) from table ";
SqlCommand sComm = new SqlCommand(str,conn_string);
num = Convert.ToInt32(sComm.ExecuteScalar());
------解决方案--------------------????
可以这样写:
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);
}
这样写,因为查询结果就只有一条;可以这样获取你要的东东!~~
------解决方案--------------------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);
}
------解决方案-------------------- 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;
}
}
}
调用这个方法,再进行强类型转换