如何在数据库查询中附加动态值?

时间:2015-12-23 09:16:44

标签: java sql string

Java代码

String ds=null;
String client=null;
List<Date> dates = new ArrayList<Date>();
String str_date ="2015-04-05";
                    String end_date ="2015-04-10";
                            int s=dates.size();
                            System.out.println("Date size value"+s);
                            for(int i=1;i<dates.size();i++){
                                Date lDate =(Date)dates.get(i);

                                 ds = formatter.format(lDate);    
                                System.out.println(" Date is ..." + ds);

                            }
                            for(int i=0;i<s;i++)
                            {
                            query0 = "SELECT  TransDate FROM abc.`"
                                    + str_date + "` WHERE `Id`='" + Id + "'";
                            query1 = "SELECT  TransDate FROM mis.`"
                                    + ds + "` WHERE `Id`='" + Id + "'";


                finalQuery = query0 + " " + " union all " + " " + query1;
                                                    }
        System.out.println("finalquery  =====   " + finalQuery);
      }

输出

I am getting output like this 
 Date size value6
 Date is ...2015-04-06
 Date is ...2015-04-07
 Date is ...2015-04-08
 Date is ...2015-04-09
 Date is ...2015-04-10
finalquery  =====   SELECT  TransDate  FROM mis.`2015-04-05` WHERE `Id`='null'  union all  SELECT  TransDate  FROM mis.`2015-04-10` WHERE `Id`='null'    
    But I need output like this 
    SELECT  TransDate  FROM mis.`2015-04-05` WHERE `Id`='null'  union all           SELECT  TransDate  FROM mis.`2015-04-06` WHERE `Id`='null' union all
    SELECT  TransDate  FROM mis.`2015-04-07` WHERE `Id`='null' union all
    SELECT  TransDate  FROM mis.`2015-04-08` WHERE `Id`='null'union all
    SELECT  TransDate  FROM mis.`2015-04-09` WHERE `Id`='null' union all
    SELECT  TransDate  FROM mis.`2015-04-10` WHERE `Id`='null'

上面的代码从日期开始,在日期之间表示。这些日期将附加在查询字符串中。请告诉我如何获得此输出....提前致谢

1 个答案:

答案 0 :(得分:0)

您每次都会覆盖循环中分配给finalQuery的值。而是将新子查询附加到现有值

finalQuery = "SELECT  TransDate FROM abc.`" + str_date + "` WHERE `Id`='" + Id 

for(int i=1;i<dates.size();i++){
   Date lDate =(Date)dates.get(i);
   ds = formatter.format(lDate);    


  for(int i=0;i<s;i++) {
      query1 = "SELECT  TransDate FROM mis.`" + ds + "` WHERE `Id`='" + Id + "'";

  }
   finalQuery = finalQuery + " " + " union all " + " " + query1;
}