SQL 命令中的字符串插值

Gra*_*ing 2 c# string string-interpolation

是否有更简单的方法在下面的插入 SQL 命令中使用namephone变量?

字符串插值是一种方法,但我不知道如何实现。

String name = textBox1.Text;
String phone = textBox2.Text;  
     
var query = "insert into Customer_info(Customer_Name,Customer_Phone) " +
            "values('" + name + "','" + phone + "');";
SqlCommand com = new SqlCommand(query,con);

try {
    con.Open();
    com.ExecuteNonQuery();
    con.Close();
}

catch (Exception Ex) {
    con.Close();
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 5

不要这样做!说真的,只是不要。字符串插值不适合构建 SQL。只需使用参数:

var query = @"
insert into Customer_info(Customer_Name,Customer_Phone)
values(@name,@phone);";
//...
cmd.Parameters.AddWithValue("name", name);
cmd.Parameters.AddWithValue("phone", phone);
cmd.ExecuteNonQuery();
Run Code Online (Sandbox Code Playgroud)

或者使用像 dapper 这样的库(它为您删除所有混乱的 ADO.NET 代码,如命令、参数和读取器):

conn.Execute(query, new { name, phone });
Run Code Online (Sandbox Code Playgroud)


Rob*_*Rob 5

您真正应该做的是使用参数化查询,因此您的查询将如下所示:

var query = "insert into Customer_info(Customer_Name,Customer_Phone)" +
"values(@name, @phone);";
Run Code Online (Sandbox Code Playgroud)

然后,您将使用一个SQLCommand对象将参数传递给查询:

using (var command = new SqlCommand(query, connection))
{
    command.Parameters.AddWithValue("@name", name);
    command.Parameters.AddWithValue("@phone", phone);

    command.ExecuteNonQuery();
}
Run Code Online (Sandbox Code Playgroud)

这样做的原因是它避免了SQL 注入的风险(这是OWASP Top 10 之一)。考虑一下您当前的查询是否name包含一些 SQL,例如,如果它包含:

'; 删除表 [Customer_info]; ——

这意味着您构造的 SQL(如果phone为空白)将如下所示:

insert into Customer_info(Customer_Name,Customer_Phone) values ('';
DROP TABLE [Customer_Info];
-- ','');
Run Code Online (Sandbox Code Playgroud)

Customer_Info如果代码连接到 SQL 的用户有足够的权限这样做,这很可能会导致您的表被删除。

  • @GragasIncoming,不,这真的不是你做的方式......你将值连接到`query`中,我将它们作为*参数*传入。这些是构造传递给 SQL Server 的查询的根本不同的方法。*请*为了任何一个公司的客户,这个代码是为它编写的,花半个小时来了解为什么串联是不好的。这是 OWASP 的一个页面,其中包含更多可能有帮助的示例:https://www.owasp.org/index.php/SQL_Injection (3认同)