How to get the result of ADO.NET SqlCommand?

Ok, either I'm really tired or really fat at the moment, but I can not find the answer to this

I am using ASP.NET and I want to find the number of rows in my table.

I know this is SQL: code select count(*) from topics, but how does HECK get it to display as a number?

All I want to do is run this code, and if it = 0 displays one thing, but if it is greater than 0 it displays something else. Help me please?

This is what I still have

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;
    }

but I know that something is seriously wrong with me. I have been looking for eternity, but I can’t find anything.

PHP is much simpler. :)

+3
source share
3 answers

, , 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;
    }
}
+10

ExecuteScalar - , . ( SqlCommand)

Btw, #, PHP. .

+1

:

SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;

cmd.CommandText = "select count(*) from topics";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection;
sqlConnection1.Open();

reader = cmd.ExecuteReader();
// Data is accessible through the DataReader object here.

sqlConnection1.Close();

: # 'select count' sql SQL-

0

All Articles