Gra*_*ing 2 c# string string-interpolation
是否有更简单的方法在下面的插入 SQL 命令中使用name和phone变量?
字符串插值是一种方法,但我不知道如何实现。
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)
不要这样做!说真的,只是不要。字符串插值不适合构建 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)
您真正应该做的是使用参数化查询,因此您的查询将如下所示:
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 的用户有足够的权限这样做,这很可能会导致您的表被删除。