我是ASP.NET和C#的新手。从我正在阅读的书中,我写了一个从数据库中获取值的SELECT语句。然而,当我在网上搜索时,程序员说这是不安全的,不应该这样做。对于C#中的新手,我怎么知道我编程的方式是错还是正确?有规则吗?例如,编写此代码的正确方法是什么:
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["CustomerDataConnectionString"].ConnectionString))
{
SqlCommand cmd = new SqlCommand("SELECT CONVERT(varchar, CAST(plan_rate AS money), 1) FROM [dbo].[plans] WHERE plan_name = '" + Dropdownbox1.Text + "'", conn);
conn.Open();
using (conn)
{
Object result = cmd.ExecuteScalar();
if (result != null)
Label6.Text = "Plan rate: $" + result.ToString();
else
Label6.Text = "Plan is not available in this state.";
conn.Close();
}
....... rest of code
答案 0 :(得分:5)
您确定此代码不安全。考虑如果Dropdownbox1.Text
包含'; DROP TABLE dbo.plans --
等恶意内容会发生什么。生成的查询将是
SELECT CONVERT(varchar, CAST(plan_rate AS money), 1)
FROM [dbo].[plans]
WHERE plan_name = '';
DROP TABLE dbo.plans --'
,您的plans
表格将被删除!
要防范这种情况,请使用参数化查询而不是字符串连接:
SqlCommand cmd = new SqlCommand("SELECT CONVERT(varchar, CAST(plan_rate AS money), 1) FROM [dbo].[plans] WHERE plan_name = @plan_name", conn);
cmd.Parameters.AddWithValue("@plan_name", Dropdownbox1.Text);
使用参数时,SQL查询引擎会将参数的值视为 data 而不是可能的命令。请在security.stackexchange.com上阅读此great answer以了解其中的差异。
在不相关的说明中,using
有两个conn
语句是不必要的;一个就够了:
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["CustomerDataConnectionString"].ConnectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT CONVERT(varchar, CAST(plan_rate AS money), 1) FROM [dbo].[plans] WHERE plan_name = @plan_name", conn);
cmd.Parameters.AddWithValue("@plan_name", Dropdownbox1.Text);
Object result = cmd.ExecuteScalar();
if (result != null)
Label6.Text = "Plan rate: $" + result.ToString();
else
Label6.Text = "Plan is not available in this state.";
}