我有一个包含大量信息的表格,现在我希望用户可以搜索该表格。
List<Table> tableSearch = new List<Table>();
string[] words = searchString.Split(' ');
string sqlSearch = "";
foreach (string word in words)
{
sqlSearch += " and Searchstring LIKE "+ "'%" + word + "%'";
}
tableSearch = db.Query<Table> ("select * from Table WHERE 1 = 1" + sqlSearch);
这是有效的,也是我想要的解决方案。
问题是,当searchString类似于Dü
,D'
时,我得到一个例外。
我在这里sqlite-net like statement crashes找到了解决问题的好方法。
我的问题是,我现在找到的唯一解决方案是:
if (words.Length < 2)
tableSearch = db.Query<Table> ("select * from Table WHERE Searchstring LIKE ?", "%" + words[0] + "%");
else if (words.Length < 3)
tableSearch = db.Query<Table> ("select * from Table WHERE Searchstring LIKE ? and Searchstring LIKE ?", "%" + words[0] + "%", "%" + words[1] + "%");
依旧......
但这不是我想要的解决方案。
有人有想法吗?
答案 0 :(得分:1)
您需要替换在SQL字符串中出错的特殊字符 例如,SQL字符串中的'字符需要替换为''。因此,我们需要修改您的代码。
List<Table> tableSearch = new List<Table>();
string[] words = searchString.Split(' ');
string sqlSearch = "";
foreach (string word in words)
{
sqlSearch += " and Searchstring LIKE "+ "'%" + word.Replace("'", "''") + "%'";
}
tableSearch = db.Query<Table> ("select * from Table WHERE 1 = 1" + sqlSearch);
要了解有关如何转义特殊字符的更多信息,请参阅以下链接 How does one escape special characters when writing SQL queries?
答案 1 :(得分:0)
我无法就重音“Du”所涉及的问题提供建议,但是D'会导致错误,因为'没有逃脱,它会干扰sql;相应地在你的第一个代码块中,
替换
sqlSearch += " and Searchstring LIKE "+ "'%" + word + "%'";
与
sqlSearch += " and Searchstring LIKE '%" + word.Replace("'","''") + "%'";
答案 2 :(得分:0)
这是编写N.Nagy答案的另一种方式,使用较少的字符串连接:
var words = (IEnumerable<string>)searchString.Split(' ').ToList();
const string SqlClause = "Searchstring LIKE '%{0}%'";
words = words.Select(word => string.Format(SqlClause, word.Replace("'", "''")));
var joined = string.Join(" AND ", words.ToArray());
const string SqlQuery = "select * from Table WHERE {0}";
var tableSearch = db.Query<Table>(string.Format(SqlQuery, joined));
因为每个人都应该了解string.Join()!!
只是为了咯咯笑:
const string SqlClause = "Searchstring LIKE '%{0}%'";
const string SqlQuery = "select * from Table WHERE {0}";
var tableSearch = db.Query<Table>(string.Format(SqlQuery, string.Join(" AND ", searchString.Split(' ').Select(word => string.Format(SqlClause, word.Replace("'", "''"))).ToArray())));
:)