我正在使用 ASP.NET,我想查找表中的行数。
我知道这是 SQL 代码:select count(*) from topics
,但是如何让它显示为数字呢?
我想做的就是运行该代码,如果它 = 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
返回一个single结果值(如果您的查询将返回多列和/或多行,则必须使用不同的方法)。
注意使用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;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)