![](/img/trans.png)
[英]Is it possible to parameterize [TestInitialize]SetUp() in c#?
[英]Is it possible to parameterize these SQL queries C#
有沒有一種簡單的方法可以將這些查詢參數化,我看過很多不同的站點,但是找不到我想要的
if (HttpContext.Current.Request.HttpMethod == "GET" && TableName != null)
{
cmd.CommandText = "SELECT TOP 50 * FROM " + TableName;
if (SearchID != null && Regex.IsMatch(SearchID, @"^\d+$"))
{
cmd.CommandText += " WHERE " + TableName + "ID Like '%" + SearchID + "%'";
}
else if (SearchName != null)
{
cmd.CommandText += " WHERE " + TableName + "Name LIKE '%" + SearchName.Replace("'", "''") + "%'";
}
if (ID != null)
{
cmd.CommandText += " WHERE " + TableName + "ID = " + ID + "";
}
}
您可以編寫使用字符串連接編寫的任何sql查詢作為sql參數化查詢,並且應該選擇最后一個,因為這是最安全的方式(避免sql注入):
更改此:
cmd.CommandText = "SELECT TOP 50 * FROM " + TableName;
if (SearchID != null && Regex.IsMatch(SearchID, @"^\d+$"))
{
cmd.CommandText += " WHERE " + TableName + "ID Like '%" + SearchID + "%'";
}
對此:
cmd.CommandText = "SELECT TOP 50 * FROM @TableName";
cmd.Parameters.Add("@TableName", TableName);
if (SearchID != null && Regex.IsMatch(SearchID, @"^\d+$"))
{
cmd.CommandText += " WHERE ID Like %@SearchID%";
cmd.Parameters.Add("@SearchID",SearchID);
}
對於其余的if
語句,您必須執行相同的操作。
注意但是,我必須承認,我從未見過將表的名稱傳遞給參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.