복붙노트

[SQL] SQL 쿼리에서 카운트를 캡처

SQL

SQL 쿼리에서 카운트를 캡처

SQL 명령의 수를 얻기 위해 C #을 (.cs 파일)에있는 가장 간단한 방법은 무엇입니까

SELECT COUNT(*) FROM table_name

int 형 변수로?

해결법

  1. ==============================

    1.사용 SqlCommand.ExecuteScalar () 및 int로 캐스팅 :

    사용 SqlCommand.ExecuteScalar () 및 int로 캐스팅 :

    cmd.CommandText = "SELECT COUNT(*) FROM table_name";
    Int32 count = (Int32) cmd.ExecuteScalar();
    
  2. ==============================

    2.

    SqlConnection conn = new SqlConnection("ConnectionString");
    conn.Open();
    SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM table_name", conn);
    Int32 count = (Int32) comm .ExecuteScalar();
    
  3. ==============================

    3.당신과 오류를 변환 얻을 것이다 :

    당신과 오류를 변환 얻을 것이다 :

    cmd.CommandText = "SELECT COUNT(*) FROM table_name";
    Int32 count = (Int32) cmd.ExecuteScalar();
    

    대신 사용

    string stm = "SELECT COUNT(*) FROM table_name WHERE id="+id+";";
    MySqlCommand cmd = new MySqlCommand(stm, conn);
    Int32 count = Convert.ToInt32(cmd.ExecuteScalar());
    if(count > 0){
        found = true; 
    } else {
        found = false; 
    }
    
  4. ==============================

    4.SQL과 C #으로 보완 :

    SQL과 C #으로 보완 :

    SqlConnection conn = new SqlConnection("ConnectionString");
    conn.Open();
    SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM table_name", conn);
    Int32 count = Convert.ToInt32(comm.ExecuteScalar());
    if (count > 0)
    {
        lblCount.Text = Convert.ToString(count.ToString()); //For example a Label
    }
    else
    {
        lblCount.Text = "0";
    }
    conn.Close(); //Remember close the connection
    
  5. ==============================

    5.

    int count = 0;    
    using (new SqlConnection connection = new SqlConnection("connectionString"))
    {
        sqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM table_name", connection);
        connection.Open();
        count = (int32)cmd.ExecuteScalar();
    }
    
  6. from https://stackoverflow.com/questions/4668911/capturing-count-from-an-sql-query by cc-by-sa and MIT license