ExecuteNonQuery for SELECT sql statement returning no rows

前端 未结 4 1764
时光取名叫无心
时光取名叫无心 2020-11-27 07:17

how do you check for no rows returned after ExecuteNonQuery for SELECT sql statement returns no rows??

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-27 07:49

    The ExecuteNonQuery Method returns the number of row(s) affected by either an INSERT, an UPDATE or a DELETE. This method is to be used to perform DML (data manipulation language) statements as stated previously.

    The ExecuteReader Method will return the result set of a SELECT. This method is to be used when you're querying for a bunch of results, such as rows from a table, view, whatever.

    The ExecuteScalar Method will return a single value in the first row, first column from a SELECT statement. This method is to be used when you expect only one value from the query to be returned.

    In short, that is normal that you have no results from a SELECT statement while using the ExecuteNonQuery method. Use ExecuteReader instead. Using the ExecuteReader method, will will get to know how many rows were returned through the instance of the SqlDataReader object returned.

    int rows = 0;
    
    if (reader.HasRows)
        while (reader.Read())
            rows++;
    
    return rows; // Returns the number of rows read from the reader.
    

提交回复
热议问题