参数化SQL查询中使用的对象类型参数数组

时间:2019-06-18 21:09:14

标签: c#

我正在对代码进行增强。有一些参数数组正在传递给我的方法。这些参数数组将传递到SQL查询中以获取数据。

为了防止可能的SQL注入,我决定使用SqlParameter的方式来处理那些参数。为了传递string[]类型的参数,this post可以很好地解决我的问题。

但是我确实有一个特殊的方法可以接受Xobject[]作为参数。例如:

public void GetDetails(CarModel[] carModels)
{
    query = "Select [MAKE],[YEAR] IN [FAKEDB].[FAKETABLE] WHERE [MAKE] " +
        "IN (*carModels makes here *) AND [YEAR] IN (*carModels years here*)"
}

假设MakeYear均为字符串类型。我是否仍可以使用SQLparameter作为此方法的解决方案?

1 个答案:

答案 0 :(得分:0)

      ///this code can help you  
        static void Main(string[] args)
          {
               string query = "Select[MAKE],[YEAR] IN[FAKEDB].[FAKETABLE] WHERE[MAKE] " +
    "IN (*Makes*) AND [YEAR] IN (*Year*)";

         CarModel[] carModels = new CarModel[2] { new CarModel() { Make = "number1", Year = "1988" },
      new CarModel() { Make = "number2", Year = "2017" }
       };
        var result = SetQueryParameter(query, carModels);
      }

       public static string SetQueryParameter(string query, CarModel[] CarModels)
      {
        var makesStr = "(";
        var yearStr = "(";
        int counter = 1;
        foreach (var item in CarModels)
        {
            makesStr += item.Make; 
            yearStr += item.Year;
            if (CarModels.Count() != counter++)
            {
                makesStr += ",";
                yearStr += ",";
            }


        }

        makesStr += ")";
        yearStr += ")";

        return query.Replace("(*Makes*)", makesStr).Replace("(*Year*)", yearStr);


    }