日期:2014-05-19  浏览次数:20574 次

VS2005里怎么把Sqlcommand执行的结果赋给变量?急等!
想写一个Sqlcommand,让它返回一张表里记录的个数,不知道怎么写才能把Sqlcommand执行的结果赋给一个变量。我写的帖在下面了,请高手指点。

SqlCommand   newsCount   =   new   SqlCommand();
        newsCount.Connection   =   new   SqlConnection( "Data   Source=.\\SQLEXPRESS;AttachDbFilename=D:\\My   Documents\\Visual   Studio   2005\\WebSites\\WebSite4\\App_Data\\ASPNETDB.MDF;Integrated   Security=True;Connect   Timeout=30;User   Instance=True ");
        newsCount.CommandText   =   "select   count(id)   from   myWebsite_News ";
        newsCount.Connection.Open();
        //这里应该怎么写呢?
        newsCount.Connection.Close();
        //Label1.Text   =怎么赋值?;


------解决方案--------------------
可以用DataAdapter dataset

string ConStr = System.Configuration.ConfigurationManager.AppSettings[ "dns "];
SqlConnection conn = new SqlConnection(ConStr);
conn.Open();
SqlDataAdapter Dap = new SqlDataAdapter( "newsview1 ", conn);
Dap.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet ds = new DataSet();
Dap.Fill(ds);
this.News_View1.DataSource = ds;
this.News_View1.DataBind();
------解决方案--------------------
SqlCommand newsCount = new SqlCommand();
newsCount.Connection = new SqlConnection( "Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\My Documents\\Visual Studio 2005\\WebSites\\WebSite4\\App_Data\\ASPNETDB.MDF;Integrated Security=True;Connect Timeout=30;User Instance=True ");
newsCount.CommandText = "select count(id) from myWebsite_News ";
newsCount.Connection.Open();
object ret = newsCount.ExecuteScalar();
if (ret is int)
{
Label1.Text =ret.ToString();
}
newsCount.Connection.Close();