在 sql 查询中使用占位符 asp.net

using placeholder in sql query in asp.net

我是一名 ASP.Net 开发人员并使用 sql 服务器 CE 4.0 我想知道如何使用此代码的占位符,因为此查询目前容易受到 sql 注入.占位符可以防止这种情况,但问题是例如 query = "SELECT * FROM TABLE WHERE TITLE = @0" 但在我的查询中动态添加 @0 的值以查询我如何使用占位符
这是代码

if (Request["search"] != "" && Request["search"] != null)
    {
        var search = Request["search"].Trim();
        string[] querynew = search.Split(' ');
        var searchquery = "and ";
        foreach (string word in querynew)
        {
            searchquery += "response_table.adtitle LIKE '%" + word + "%' OR ";
        }
        sql += searchquery.Remove(searchquery.Length - 4);
    }
    if (Request["min"] != "" && Request["min"] != null && Request["max"] != null && Request["max"] != "")
    {
        sql = sql + " and (CAST(response_table.price AS Float)) between " + Request["min"].Trim() + " AND " + Request["max"].Trim();
    }
    // 3. the order clause    

    switch (Request["sort"])
    {
        case "recent":
            sql = sql + "ORDER BY response_table.response_ID DESC OFFSET " + offset + " ROWS FETCH NEXT " + pageSize + " ROWS  ONLY";
            break;
        case "hightolow":
            sql = sql + "ORDER BY CAST(response_table.price AS Float) Desc OFFSET " + offset + " ROWS FETCH NEXT " + pageSize + " ROWS  ONLY";
            break;
        case "lowtohigh":
            sql = sql + "ORDER BY CAST(response_table.price AS Float) ASC OFFSET " + offset + " ROWS FETCH NEXT " + pageSize + " ROWS  ONLY";
            break;
        default:
            break;
    }
    result = db.Query(sql);

谢谢

使用参数(而不是连接字符串)可以优化查询的性能。

您可以使用 SqlCeCommand. It has a collection of parameters and you can find a sample here 了解如何使用它们。