1

所以我有一个名为 arr 的 ArrayList,其中包含诸如“decoration”、“metal”、“paper”等字符串。

我想要做的是循环遍历该 ArrayList,将每个标签添加到查询字符串中,使用该查询字符串从数据库中获取数据。目前我有这样的事情:

String strSel="select * from Table1 where Tags";

for(int x=0;x<arr.Count;x++){
  if (x == arr.Count - 1)
    {
      strSel += " like '%'"+arr[x]+"'%'";
    }
      else
    {
      strSel += " like '%'" + arr[x] + "'%' or Tags";
    }
}

cmdSel=new SqlCommand(strSel,connectionName);
sqlDataReaderName=cmdSel.ExecuteReader();

无论如何,我收到一个关于“bla 附近语法不正确”的错误......它可能与单引号或通配符有关,但我无法弄清楚。我究竟做错了什么?

4

2 回答 2

2

您应该_ _percent symbol

strSel += " like '%" + arr[x] + "%'";

抛出错误的原因是因为您的查询是这样形成的

select * from Table1 where Tags like '%'hello'%'
                                       ^     ^ extra single quote that
                                               should be removed
于 2012-11-27T00:08:29.813 回答
0

是的 Kuya John 是正确的,额外的 ' 是导致问题的原因

        String strSel = "select * from Table1 where Tags";
        string[] arr = new string[] { "This", "That", "Something" };
        for (int x = 0; x < arr.Count(); x++)
        {
            if (x == arr.Count() - 1)
            {
                strSel += string.Format(" like '%{0}%' ", arr[x]);
            }
            else
            {
                strSel += string.Format(" like '%{0}%' or Tags", arr[x]);
            }
        }

这在没有额外的 ' 的情况下表现良好

于 2012-11-27T00:17:20.323 回答