如何检索ADO.NET SqlCommand的结果?

dpD*_*gnz 4 c# sql-server asp.net select

好吧,我现在真的很累或很厚,但我似乎无法找到答案

我正在使用ASP.NET,我想在表中找到行数.

我知道这是SQL代码:select count(*) from topics但是HECK如何将其显示为数字?

我想要做的只是运行该代码,如果它= 0显示一件事,但如果它超过0显示其他东西.请帮忙?

这就是我到目前为止所拥有的

string selectTopics = "select count(*) from topics";
// Define the ADO.NET Objects
SqlConnection con = new SqlConnection(connectionString);
SqlCommand topiccmd = new SqlCommand(selectTopics, con);
if (topiccmd == 0)
    {
        noTopics.Visible = true;
        topics.Visible = false;
    }
Run Code Online (Sandbox Code Playgroud)

但我知道我错过了一些严重的错误.我一直在寻找年龄但找不到任何东西.

PHP非常简单.:)

Gra*_*tzy 13

请注意,必须先打开连接并执行命令,然后才能访问SQL查询的结果.ExecuteScalar返回单个结果值(如果查询将返回多列和/或多行,则必须使用不同的方法).

注意using构造的使用,它将安全地关闭和处理连接.

string selectTopics = "select count(*) from topics";
// Define the ADO.NET Objects
using (SqlConnection con = new SqlConnection(connectionString))
{
   SqlCommand topiccmd = new SqlCommand(selectTopics, con);
   con.Open();
   int numrows = (int)topiccmd.ExecuteScalar();
   if (numrows == 0)
    {
        noTopics.Visible = true;
        topics.Visible = false;
    }
}
Run Code Online (Sandbox Code Playgroud)