如何更改sql'喜欢'操作员动态?

时间:2014-09-04 11:11:25

标签: java mysql sql database oracle11g

在我的下面的代码中,我想动态地检索数据库内容。但问题是最终条件。我该怎么改变?

    string qry= "SELECT Data_Sentences FROM table1 Where";
    For(i=0;i<arraylenth;i++)
    {
    qry+= " Data_sentences like '%" + array[i].tostring() + "%' OR";
    }qry += " 1=1";

在此代码中,最终条件1 = 1出错了。检索所有句子。我应该如何更改才能获得预期的句子?

3 个答案:

答案 0 :(得分:1)

您发布的代码存在一些问题。

  • 循环内的原始String连接非常糟糕。如果需要线程安全,请使用StringBuilder(或StringBuffer来代替。
  • OR 1 = 1将永远为真,因此每一行都符合标准并被退回。

您可以选择以下几种方式:

StringBuilder qry = new StringBuilder(
        "SELECT Data_Sentences FROM table1 WHERE 1 = 1");
for (int i = 0; i < array.length; i++) {
    if (i == 0) {
        qry.append(" AND (Data_sentences LIKE '%" + array[i].toString() + "%'");
    } else {
        qry.append(" OR Data_sentences LIKE '%" + array[i].toString() + "%'");
    }

    if (i == array.length - 1) {
        qry.append(")");
    }
}

这个将1 = 1条件移动到基​​本字符串中,因为它总是会被追加。它还会改变OR条件的形式,产生一个查询,例如(为便于阅读而格式化):

SELECT Data_Sentences
  FROM table1
 WHERE 1 = 1
   AND (Data_Sentences LIKE '%some value%'
        OR Data_Sentences LIKE '%some other value%')

显然此查询的格式与原始查询的格式不同,但应以相同的方式运行。或者,您可以这样做:

StringBuilder qry = new StringBuilder(
        "SELECT Data_Sentences FROM table1 WHERE");
for (int i = 0; i < array.length; i++) {
    qry.append(" Data_sentences LIKE '%" + array[i].toString() + "%' OR");
}
qry.append(" 1 = 0");

这将产生与您当前查询非常相似的内容(为便于阅读而再次格式化):

SELECT Data_Sentences
  FROM table1
 WHERE Data_Sentences LIKE '%some value%'
    OR Data_Sentences LIKE '%some other value%'
    OR 1 = 0

我还没有执行任何测试来查看哪些查询会更有效,但如果我不得不猜测我会说其中OR s更少的查询会更快两者,但差异(如果有的话)可以忽略不计。

第三种选择是首先检查array的长度,如果WHERE大小为0则完全跳过{{1}}条款。

答案 1 :(得分:0)

只需将其更改为1=0

string qry= "SELECT Data_Sentences FROM table1 Where";
For(i=0;i<arraylenth;i++)
{
qry+= " Data_sentences like '%" + array[i].tostring() + "%' OR";
}qry += " 1=0";

当连接符为1=1时使用AND

答案 2 :(得分:0)

如果没有这个有趣的1 = 1或1 = 0虚拟条件会更有意义。

string qry= "SELECT Data_Sentences FROM table1 Where";
For(i=0;i<arraylenth;i++)
{
    qry+= " Data_sentences like '%" + array[i].tostring() + "%'";
    if (i < arraylenth-1)
        qry+= " OR";
}