簡體   English   中英

如何從sql數據庫中檢索asp.net mvc中的行數?

[英]How to retrieve the count of the number of rows in asp.net mvc from sql database?

我試圖打印一些東西,如果根據查詢返回的行數大於0:

using (SqlConnection con = new SqlConnection("ConnectionString")){
  con.Open();
  string query = "SELECT COUNT(*) FROM Some_Table WHERE Val > 5";
  SqlCommand cmd = new SqlCommand(query, con);
  cmd.ExecuteNonQuery(); // get the value of the count
  if (count > 0) 
  {
    Console.WriteLine("Returned more than 0 rows");
  }
  else
  {
    Console.WriteLine("Did not return more than 0 rows");
  }
  Console.ReadLine();
}

如何找到返回的行數?

即使沒有行,您的查詢也會返回一行。 如果您的WHERE條件不存在任何行,它將返回0

使用SqlCommand.ExecuteScalar方法()

using (var con = new SqlConnection("ConnectionString"))
{
  con.Open();
  string query = "SELECT COUNT(*) FROM Some_Table WHERE Val > 5";

  using (var cmd = new SqlCommand(query, con))
  {
      int rowsAmount = (int)cmd.ExecuteScalar(); // get the value of the count
      if (rowsAmount > 0) 
      {
          Console.WriteLine("Returned more than 0 rows");
      }
      else
      {
          Console.WriteLine("Did not return more than 0 rows");
      }

      Console.ReadLine();
}

ScalarValue將返回第一行查詢結果的第一列。 因此,對於您的查詢,這是檢索所需信息的更有效方法。

你可以這樣做,因為ExecuteNonQuery - 返回受影響的行數。

int numberOfRecords = cmd.ExecuteNonQuery();
if (numberOfRecords  > 0) 
{
  Console.WriteLine("Returned more than 0 rows");
}
else
{
    Console.WriteLine("Did not return more than 0 rows");
}

SQLClient Command對象的ExecuteScalar()方法專門用於從查詢返回單個值。 它在代碼和性能方面更有效。

using (SqlConnection conn = new SqlConnection("ConnectionString"))
{
conn.Open();
string query = "SELECT COUNT(*) FROM Some_Table WHERE Val > 5";
SqlCommand command = new SqlCommand(query, con);
Int32 count = (Int32) cmd.ExecuteScalar()
}

使用DataSet獲取計數

SqlCommand cmd = new SqlCommand(query, con);

SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();

da.Fill(ds);

var count = ds.Tables[0].Rows.count;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM