![](/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.