gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 15:12:44 24 4
gpt4 key购买 nike

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

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