1
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.

2
  • 5
    You have a SQL injection vulerability. Commented May 18, 2017 at 16:40
  • Possible duplicate of Capturing count from an SQL query Commented Dec 5, 2017 at 18:33

2 Answers 2

9
  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";
Sign up to request clarification or add additional context in comments.

5 Comments

since the name of his method is checkIfExists, it would probably be better to just grab the indexed key and call .HasRows. It would be a little faster and clearly define what he wants (assuming what he says he wants doesn't actually match his method name, since it doesn't return a bool either).
@Dispersia That is certainly true. I wanted OP to concentrate on the basics, though, so that he could eliminate a critical vulnerability and get an answer to his query first, and worry about the performance later. Good chances are, he'll find performance of this solution acceptable, and wouldn't worry about optimizing it any further.
This is true, was just food for thought more for the OP, since his method naming and return types don't even really match up :)
The @Name will get the name variable received in the method or do I have to create a parameter?
@RafaelDuarte You need to create a parameter, and set its value to method's parameter Name (C# naming conventions suggest lower case for n in name). Follow the first link in the answer for info on how to work with parameters. There's more than one way; different answers from that linked Q&A show code examples.
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.