【问题标题】:JDBC 4 order by clauseJDBC 4 order by 子句
【发布时间】:2012-04-09 18:58:09
【问题描述】:

我可以有一个包含以下查询的准备好的语句:

select * from table as t order by ? ? limit ?,? 

第二个“?”将是 asc 或 desc。

【问题讨论】:

    标签: java mysql jdbc


    【解决方案1】:

    如果列和排序方向的组合是有限的,并且语句不是过于复杂,你可以用 union 来模拟它。但这不是很优雅。语句必须存在 n 次,参数标记也必须存在 n 次。如果你使用 springs jdbc-template 之类的框架,你可以命名参数,并且没有计算参数位置错误的危险。

    select * from table where ? = 'col1' and ? = 'asc' order by col1 asc
    union all
    select * from table where ? = 'col1' and ? = 'desc' order by col1 desc
    union all
    select * from table where ? = 'col2' and ? = 'asc' order by col2 asc
    union all
    select * from table where ? = 'col2' and ? = 'desc' order by col2 desc
    ...
    

    【讨论】:

      【解决方案2】:

      这是不可能的,请看这里:

      在声明中,“?”字符可以用作参数标记 指示稍后何时将数据值绑定到查询的位置 你执行它。这 ”?”字符不应包含在 引号,即使您打算将它们绑定到字符串值。 参数标记只能在数据值应该出现的地方使用, 不适用于 SQL 关键字、标识符等。

      MySQL documentation

      【讨论】:

        【解决方案3】:

        尝试它确实是最好的事情。我不相信您可以绑定表名或列名,只能绑定参数。所以我的回答是“不”,你不能。但是回答这种问题的最好方法是尝试一下。它会比在这里询问更快、更明确。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-09-07
          • 2018-03-23
          • 1970-01-01
          • 2017-12-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-04-10
          相关资源
          最近更新 更多