【问题标题】:Dynamic search using sql queries使用 sql 查询进行动态搜索
【发布时间】:2014-10-14 09:07:14
【问题描述】:

我正在我的应用程序中实现动态搜索,我有以下选项来构建查询。

  1. 来自用户输入的字符串连接
  2. 使用多个查询,并根据用户输入提取正确的查询
  3. 使用一个查询,对用户未提供的输入使用通配符。

例如:

select * from A,B where a.id like nvl( {input}, '%')
and a.id = b.aid
and b.value like nvl({input2},'%');

因为 id 是主键,我在尝试时在 oracle 中收到以下错误。

【问题讨论】:

  • 不要选择选项 1,因为您的应用程序将容易受到 SQL 注入和跨站点脚本等攻击。在使用查询中的变量之前还要验证您的输入。
  • 关于通配符,如果我理解您的问题,Java PreparedStatement 似乎很适合这种情况。

标签: java sql oracle dynamic-queries


【解决方案1】:

首先,对于通配符搜索,您需要使用LIKE 谓词,而不是=。其次,很明显,您不能将LIKE 谓词用于数字数据。你可以做的是:

select * from A,B where ( a.id = {input} or {input} is null )...

【讨论】:

  • 好的。明天试试。谢谢。
【解决方案2】:

一个简单的解决方案可能是:

StringBuffer sqlSB = new StringBuffer("select * from A,B where a.id = b.aid ");
if(input!=null&&!input.equals("")){
    sqlSB.append(" and a.id = ").append(input);
}
if(input2!=null&&!input2.equals("")){
    sqlSB.append(" and b.value = '").append(input2).append("' ");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    相关资源
    最近更新 更多