简体   繁体   中英

C# Count number of rows in sql result

Connection c = new Connection();
public string checkIfExists(string Name)
    {
        string sql = "SELECT * FROM users WHERE name = '" + name + "'";
        c.Execute(sql);

        return "";
    }

The c.Execute(sql) is calling a SqlCommand function to execute the sql query.

I want to know how to count the number of rows retrieved by this query.

Ignore the return.

  1. Make sure your SQL is protected from SQL injection attack by parameterizing it
  2. Rewrite SQL to return COUNT
  3. Use ExecuteScalar to retrieve the answer

The query should look like this:

var sql = "SELECT COUNT(*) FROM users WHERE name = @Name";

Here is Sam SQL query:

SELECT COUNT(1) FROM nazvaniyami
SQL query with condition:

SELECT COUNT(1) FROM nazvaniyami WHERE condition
Implementation in PHP:

$a = mysql_query("SELECT COUNT(1) FROM navaneetham");
$b = mysql_fetch_array( $a );
echo $b[0]; // prints the number of rows

Likewise, it is possible to add a condition. Then the code prints the number of rows in the table satisfying the condition. Thank you for your attention, with you was Maxim

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM