gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:08:16 25 4
gpt4 key购买 nike

好吧,要么我现在真的很累,要么真的很胖,但我似乎找不到答案

我正在使用 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;
}

但我知道我遗漏了一些严重的错误。我一直在寻找多年,但找不到任何东西。

PHP 简单多了。 :)

最佳答案

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com