我正在开发一个基于新闻的网站。该网站有一个Newstitle的搜索栏,我不想让SQL注入发生。
我正在做的是从文本框获取文本,然后使用查询来获取匹配的结果。当用户点击搜索按钮时会发生这种情况:
protected void button_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
SqlConnection conn = new SqlConnection(connectionString);
try
{
SqlCommand comm = new SqlCommand("SELECT * FROM news
Where newstilte LIKE '%" + searchbox.text + "%'", conn);
conn.Open();
SqlDataReader reader = comm.ExecuteReader();
myRepeater.DataSource = reader;
myRepeater.DataBind();
reader.Close();
}
catch (Exception exception)
{
Response.Write(exception.ToString());
}
finally
{
conn.Close();
}
}
如您所见,然后我使用转发器来显示结果。我想知道如何在人们用文本框编写的部分中防止SQL注入。
答案 0 :(得分:3)
如下所示使用参数化的查询:
protected void button_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
SqlConnection conn = new SqlConnection(connectionString);
try
{
SqlCommand comm = new SqlCommand("SELECT * FROM news
Where newstilte LIKE '%' + @newstilte + '%'", conn);
cmm.Parameters.AddWithValue("@search",searchbox.text) ;
conn.Open();
SqlDataAdapter reader = comm.ExecuteReader();
myRepeater.DataSource = reader;
myRepeater.DataBind();
reader.Close();
}
catch (Exception exception)
{
Response.Write(exception.ToString());
}
finally
{
conn.Close();
}
}
修改强>
如果您有数据类型的搜索限制,也可以使用以下内容。
cmm.Parameters.Add(new SqlParameter("@search", SqlDbType.VarChar));
cmm.Parameters["@search"].Value = searchbox.text;
查看THIS doccument。
答案 1 :(得分:1)
尝试
SqlCommand comm = new SqlCommand("SELECT * FROM news
Where newstilte LIKE '%' + @newstilte + '%'", conn);
comm.Parameters.AddWithValue("@newstilte",searchbox.text)
答案 2 :(得分:1)
使用带参数的存储过程。
.net SQL库正确
SqlCommand comm = new SqlCommand("StoredProcedureName")
comm.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("@Parameter", Value)
.net库应该处理大多数注射。