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

标签 c# asp.net sql-server select

我正在使用 ASP.NET,我想查找表中的行数。

我知道这是 SQL 代码:从主题中选择 count(*),但如何将其显示为数字?

我想做的就是运行该代码,如果它= 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;
    }

我错过了什么?

最佳答案

请注意,您必须打开连接并执行命令,然后才能访问 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;
    }
}

关于c# - 如何检索 ADO.NET SqlCommand 的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59944111/

相关文章:

c# - HttpUtility.ParseQueryString 缺少一些字符

c# - 像 MessageBox 或 Dialog 一样暂停执行

asp.net - 有哪些学习 rdlc 报表设计的好教程网站?

c# - 如何在 C# 中处理对 Web 只读 TextBox 的单击事件

c# - 检查表是否存在 : Table doesn't exist while it exists

sql-server - SSIS 集合中的通配符{不包括}名称 xlsx

c# - 如何在 C# 中对开放类型进行泛型多态?

asp.net - 有哪些选项可用于在 ASP.NET MVC2 中存储应用程序设置?

sql-server - 使用左连接在单个更新语句中更新多个表

c# - 如何在鼠标悬停时自定义工具条按钮突出显示颜色