我正在对代码进行增强。有一些参数数组正在传递给我的方法。这些参数数组将传递到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*)"
}
假设Make
和Year
均为字符串类型。我是否仍可以使用SQLparameter
作为此方法的解决方案?
答案 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);
}