SQL Server How do I retrieve the result of an ADO.NET SqlCommand?

mwg9r5ms  于 2023-06-04  发布在  .NET
关注(0)|答案(3)|浏览(147)

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:

  1. string selectTopics = "select count(*) from topics";
  2. // Define the ADO.NET Objects
  3. SqlConnection con = new SqlConnection(connectionString);
  4. SqlCommand topiccmd = new SqlCommand(selectTopics, con);
  5. if (topiccmd == 0)
  6. {
  7. noTopics.Visible = true;
  8. topics.Visible = false;
  9. }

What am I missing?

qlckcl4x

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.

  1. string selectTopics = "select count(*) from topics";
  2. // Define the ADO.NET Objects
  3. using (SqlConnection con = new SqlConnection(connectionString))
  4. {
  5. SqlCommand topiccmd = new SqlCommand(selectTopics, con);
  6. con.Open();
  7. int numrows = (int)topiccmd.ExecuteScalar();
  8. if (numrows == 0)
  9. {
  10. noTopics.Visible = true;
  11. topics.Visible = false;
  12. }
  13. }
展开查看全部
5t7ly7z5

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.

im9ewurl

im9ewurl3#

You need to open the connection This might work :

  1. SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
  2. SqlCommand cmd = new SqlCommand();
  3. SqlDataReader reader;
  4. cmd.CommandText = "select count(*) from topics";
  5. cmd.CommandType = CommandType.Text;
  6. cmd.Connection = sqlConnection;
  7. sqlConnection1.Open();
  8. reader = cmd.ExecuteReader();
  9. // Data is accessible through the DataReader object here.
  10. sqlConnection1.Close();

Similar Question: C# 'select count' sql command incorrectly returns zero rows from sql server

相关问题