Tutorial :Adding variable to string in ASP.net



Question:

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!


Solution:1

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);  


Solution:2

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.


Solution:3

use the '+' instead of the '&'


Solution:4

+ is the string concatenation operator in C#.


Solution:5

Use a "+" instead of "&"

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


Solution:6

Use + instead

i.e.

'" + username + "'"  


Solution:7

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);  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »