0
UPDATE處理數據選擇特殊字符輸入
以下四個字符需要時逃脫 '\' 是轉義幫手%[]_
- http://msdn.microsoft.com/en-us/library/aa933232(v=sql.80).aspx - LIKE
- Escape a string in SQL Server so that it is safe to use in LIKE expression
- How do I escape _ in SQL Server?
問題
儘管我搜索了很多,但在堆棧溢出中找不到與以下內容完全匹配的問題。
我有一個名爲Log_Description的數據庫列。它有兩個記錄。
1) 「樣品%值記錄」
2) 「樣品自由記錄」
我使用SQL命令和如下所示
commandText = commandText + 「Log_Description LIKE @Log_Description」;
command.Parameters.AddwithValue(「@Log_Description」, 「%」+obj. LogDescription+」%」);
設置參數假設用戶輸入「 %「作爲txtLogDescription文本框的搜索參數,我只需要顯示第一條記錄。但目前它正在顯示這兩個記錄。
- 什麼是可能的方式來解決這個?
- 什麼是可能導致與上面的代碼此類問題的其他角色?
注:我不能阻止用戶進入「%」作爲輸入
注:我使用的SQL Server數據庫
編輯:
解決方案我現在用的就是Escaping the escape character does not work – SQL LIKE Operator
private static string CustomFormat(string input)
{
input = input.Replace(@"\", @"\\");
input = input.Replace(@"%", @"\%");
input = input.Replace(@"[", @"\[");
input = input.Replace(@"]", @"\]");
input = input.Replace(@"_", @"\_");
return input;
}
LINQ方法(與性能損失)低於
Collection<Log> resultLogs = null;
if (!String.IsNullOrEmpty(logSearch.LogDescription))
{
resultLogs = new Collection<Log>();
var results = from o in logs where o.LogDescription.Contains(logSearch.LogDescription) select o;
if (results != null)
{
foreach (var log in results)
{
resultLogs.Add((Log) log);
}
}
}
else
{
resultLogs = logs;
}
什麼數據庫您使用的?SQL Server,Oracle,MySQL? –
如果你使用的是SQL Server,那麼這裏有一個類似的問題http://stackoverflow.com/a/258947/1045728,基本上你會轉義在搜索值中找到的任何% –
請參閱http://stackoverflow.com/questions/ 13861004 /逃避最轉義字符不 - 不工作類似於SQL的運營商 – Lijo