开发者

Adding variable to string in ASP.net

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

SqlCommand cmd = new SqlCommand("SELECT COU开发者_Go百科NT(*) 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!


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


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.


use the '+' instead of the '&'


+ is the string concatenation operator in C#.


Use a "+" instead of "&"

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


Use + instead

i.e.

'" + username + "'"


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜