简体   繁体   English

在ASP.net中将变量添加到字符串

[英]Adding variable to string in ASP.net

Ok, so it's easy in VB, but I can't figure it out in C#: 好的,所以在VB中很容易,但是我无法在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! 用谷歌搜索,找不到答案,请在这里帮助这个新手!

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. 您使用的方法容易受到SQL注入攻击。

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. 但是,从长远来看,最好使用参数化查询,而不是直接将变量连接到SQL语句中。 By concatenating, especially if that's user input, you are wide open for SQL injection attacks. 通过串联(尤其是在用户输入的情况下),您可以对SQL注入攻击敞开大门。 By using parameters, you block SQL injection. 通过使用参数,您可以阻止SQL注入。

SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM tblUsers WHERE username = @user");
cmd.Parameters.AddWithValue("@user",  username);

使用“ +”代替“&”

+是C#中的字符串连接运算符。

Use a "+" instead of "&" 使用“ +”代替“&”

SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM tblUsers WHERE username = '" + username + "'", cn); SqlCommand cmd =新的SqlCommand(“从tblUsers那里的SELECT COUNT(*)用户名='” +用户名+“'”,cn);

Use + instead 使用+代替

ie

'" + username + "'"

我更喜欢这种类型的另一个选项是String.Format:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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