0

Ok, so it's easy in VB, but I can't figure it out in C#:

SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM tblUsers WHERE username = '" & username & "'", cn);

This throws

 CS0019: Operator '&' cannot be applied to operands of type 'string' and 'string'

Googled it and can't find an answer, help this newbie here please!

7
  • Use + operator instead of & operator. Commented Aug 5, 2010 at 14:46
  • SELECT COUNT(*) FROM tblUsers WHERE username = '" + username + " OR 1=1'", cn); Commented Aug 5, 2010 at 14:52
  • Paco, what does that achieve? Commented Aug 5, 2010 at 14:53
  • All the users will be removed from the database. Commented Aug 5, 2010 at 14:58
  • 1
    @Tom, sad experience says that it's not possible to write a "sanitizing" filter that's as smart as the accumulated knowledge of hackers. Parameters are the only safe way to prevent SQL injection. Commented Aug 5, 2010 at 15:06

7 Answers 7

3

You've already got six (and counting) recommendations to use + instead of &. However, you'd be much better off in the long run to use a parameterized query instead of concatenating a variable directly into the SQL statement. By concatenating, especially if that's user input, you are wide open for SQL injection attacks. By using parameters, you block SQL injection.

SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM tblUsers WHERE username = @user");
cmd.Parameters.AddWithValue("@user",  username);
Sign up to request clarification or add additional context in comments.

2 Comments

Excellent point, +1. I'd not really looked at the overall problem there and yes, you should usually be using sql parameters for this sort of thing.
It should be said that I always sanitise my input before running it in a query, I am aware of the pitfalls of SQL injections, but this seems like another good defence.
3

Use + to concatentate strings. & functions as either a unary or a binary operator.

However, the correct answer is to use parameterized queries!

The method you are using is subject to SQL injection attacks.

Comments

2

use the '+' instead of the '&'

Comments

2

+ is the string concatenation operator in C#.

Comments

2

Use a "+" instead of "&"

SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM tblUsers WHERE username = '" + username + "'", cn);

Comments

2

Use + instead

i.e.

'" + username + "'"

Comments

2

The other option which I prefer for this sort of thign is String.Format:

SqlCommand cmd = new SqlCommand(String.Format("SELECT COUNT(*) FROM tblUsers WHERE username = '{0}'",username ), cn);

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.