巧妙地将相同参数添加到prepared-statement中的多个位置

时间:2010-07-16 11:18:03

标签: java jdbc union prepared-statement

我有像

这样的JDBC查询
select * from table1 where col1 between x and y
union all
select * from table2 where col1 between x and y
union all
select * from table3 where col1 between x and y

我正在使用预备语句,我想知道是否有一种更聪明的方法来设置x和y而不说setDate(1, x);setDate(2, y);setDate(3, x);

4 个答案:

答案 0 :(得分:0)

聪明。也许一个循环?执行三次并调用的for循环:

setDate((1*2)+1, x);
setDate((1*2)+2, y);

答案 1 :(得分:0)

如果你的数据库很不错,你可以这样做:

select * from (
select * from table1 
union all
select * from table2
union all
select * from table3
)
where col1 between x and y

并仅传递xy一次。如果合适,优化器会将谓词应用于每个表。

答案 2 :(得分:0)

为什么要“聪明”?聪明的代码通常会在“聪明的”角落案例中产生“聪明”的错误。

顺便说一句,如果你使用休眠,你的查询将是:

select * from table1 where col1 between :x and :y
union all
select * from table2 where col1 between :x and :y
union all
select * from table3 where col1 between :x and :y

Java代码如下所示:

Query query;
query.setParameter("x", x);
query.setParameter("y", y);

答案 3 :(得分:-3)

我会利用java的String Formatter:

String queryFormat = "select * from table1 where col1 between %1$s and %2$s " +
                     "union all " +
                     "select * from table2 where col1 between %1$s and %2$s " +
                     "union all " +
                     "select * from table3 where col1 between %1$s and %2$s";
String query = String.format(queryFormat,"5","10");

传递给format方法的第一个参数是格式字符串。 %1$s表示插入 s tring(“5”)类型的 1 st参数,%2$s表示插入 2 类型 s tring(“10”)的参数。

然后查询字符串将包含:

select * from table1 where col1 between 5 and 10 union all select * from table2 where col1 between 5 and 10 union all select * from table3 where col1 between 5 and 10

您可以阅读有关Formatter类here的更多信息。

希望这有帮助。