I'm using ASP.NET and I want to find the amount of rows in my table.
I know this is the SQL code: select count(*) from topics
, but how do I get that to display as a number?
All I want to do is run that code and if it = 0 display one thing but if it's more than 0 display something else.
This is what I have so far:
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;
}
What am I missing?
3条答案
按热度按时间qlckcl4x1#
Note that you must open the connection and execute the command before you can access the result of the SQL query.
ExecuteScalar
returns a single result value (different methods must be used if your query will return an multiple columns and / or multiple rows).Notice the use of the
using
construct, which will safely close and dispose of the connection.5t7ly7z52#
ExecuteScalar is what you're looking for. (method of SqlCommand)
Btw, stick with C#, there's no way PHP is easier. It's just familiar.
im9ewurl3#
You need to open the connection This might work :
Similar Question: C# 'select count' sql command incorrectly returns zero rows from sql server