用户输入搜索charactre,如* “蓝色,黄绿色,红色粉红色,叠加流量” * 现在我想把它放到数组中,并使用以下代码搜索它,
string[] search = mysearch.Split(',');
List<Result> myresult = new List<Result>();
for (int kk = 1; kk < search.Length; kk++)
{
where += " And '%" + search[kk] + "%'";
OleDbCommand sqlcmdCommand0 = new OleDbCommand("select Distinct name from table1 where search like '%" + search[0] + "%' " + where + " order by name", myCon);
sqlcmdCommand0.CommandType = CommandType.Text;
OleDbDataReader sda = sqlcmdCommand0.ExecuteReader();
while(sda.read())
{
myresult.name= sda.getString(0);
Result.add(myresult);
}
}
return Result;
查询看起来像这样:
select Distinct name from table1 where search like '%blue%' And '%yellow%' And '%Green %' order by name
它应该看起来像这样:
select Distinct name from table1 where search like '%blue%' And '%yellow Green %' order by name
但问题是它在空格不在逗号之后分隔字符串,并且我想在逗号出现之后将字符串放入数组中,而不是在字符之间的空格之后。
答案 0 :(得分:2)
好的,我想您可能只想丢弃当前的代码......以下是生成WHERE
条件所需要做的事情:
string[] searchTerms = mySearch.Split(',');
StringBuilder conditions = new StringBuilder();
foreach(string term in searchTerms)
{
if (conditions.Length > 0)
conditions.Append(" AND ");
conditions.AppendFormat("search LIKE '%{0}%'", term.Replace("'", "''"));
}
string query = "select Distinct name from table1";
if (conditions.Length > 0)
query = query + " WHERE " + conditions;
答案 1 :(得分:0)
您的SQL不正确,每次比较需要like
运算符,每个运算符需要两个操作数。此外,您可能希望在比较之间使用or
运算符,否则您只会找到包含所有颜色的记录,而不是任何颜色:
select Distinct name
from table1
where
search like '%blue%' or
search like '%yellow%' or
search like '%green%'
order by name
答案 2 :(得分:-1)
如果你想在逗号和空格上拆分,请使用带有params参数的重载,并传递一个逗号char和一个空白字符:
"red, blue green".Split(',', ' ');