SQL注入prevention在.NETSQL、prevention、NET

2023-09-03 02:04:43 作者:薄情已负

我通常写我的SQL为使在.NET

I typically write my SQL as so in .NET

sql.Append("SELECT id, code, email FROM mytable WHERE variable = @variable ");

然后做这样的事情:

Then do something like this:

using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[ConfigurationManager.AppSettings["defaultConnection"]].ConnectionString))
{
    using (SqlCommand myCommand = new SqlCommand(sql.ToString(), conn))
    {
        myCommand.Parameters.AddWithValue("@variable", myVariableName");
        ...

不过,我也应该这样做addParameter的时候,我得到了数据直接来自数据库,像这样?

But should I also do this addParameter when the data I got comes directly from the database like so?

likesql.Append(string.Format("SELECT group_id, like_text FROM likeTerms ORDER BY group_id ASC "));

DataTable dtLike = SqlHelper.GetDataTable(likesql.ToString());

foreach (DataRow dr in dtLike)
{
    buildsql.Append(".... varId = " + dr["group_id"].ToString() + "...");

    ...

这是可以接受的?什么是最好的做法?

Is this acceptable? What is best practice?

推荐答案

在哪里从?您的数据库里的值 您能相信,在你的榜样,那GROUP_ID没有被修改要的东西你不期待?

You should always use parameters:

Where are the values in your database coming from? Can you trust, in your example, that 'group_id' wasn't modified to be something you're not expecting?

有人可以用有限的数据库访问直接注入到其他地方的一个领域?

Can someone with limited database access inject directly into a field used elsewhere?

此外,它有助于提高性能。高速缓存的执行计划,将忽略该参数的值,这意味着你的每次参数变化重新编译查询可以节省服务器。

Also, it helps performance. Cached execution plans will disregard the value of the parameter, meaning you're saving the server from recompiling the query every time the parameters change.