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

前端 未结 3 1548
说谎
说谎 2020-12-11 07:03

Ok either I\'m really tired or really thick at the moment, but I can\'t seem to find the answer for this

I\'m using ASP.NET and I want to find the amount of rows in

相关标签:
3条回答
  • 2020-12-11 07:29

    You need to open the connection This might work :

    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();
    

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

    0 讨论(0)
  • 2020-12-11 07:34

    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.

    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;
        }
    }
    
    0 讨论(0)
  • 2020-12-11 07:36

    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.

    0 讨论(0)
提交回复
热议问题