2011-08-17 98 views
2

我想在ORACLE sql代码中创建条件语句 我在java中有一个需要2个参数的函数。 的GetChildren(child1,的child2) ..this函数的参数是用来创建一个查询语句SQL条件语句

public ResultSet getchildren(String Child1, String child2) throws SQLException 
{ 

stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, 
ResultSet.CONCUR_READ_ONLY); 


    query ="select * from table1 

      if child1 is not null and child2 is null 
      { where child1 = 1 } 
      else if child2 is not null AND child1 is null 
      {where child2 = 2} 
      else 
      {//some other where statment } 
      "; 



    System.out.println("\nExecuting query: " + query); 
    rset = stmt.executeQuery(query); 

    return rset; 


} 

这显然是伪代码。 我需要帮助创建的条件执行,其中子句,以便每个“where”子句在条件有效时执行。我尝试了类似于我在那里但与没有运气的东西。

回答

3

使用StringBuilder动态构建您的查询。

StringBuilder queryBuilder = new StringBuilder(); 
queryBuilder.append("select * from table1 "); 

if (child1 != null && child2 == null) 
    queryBuilder.append(" where child1 = 1 "); 
else if (child2 != null && child1 == null) 
    queryBuilder.append(" where child2 = 1 "); 
else 
    queryBuilder.append(" where bla "); 

// Execute queryBuilder.toString(); 
rset = stmt.executeQuery(queryBuilder.toString()); 
+0

感谢您的回答! – Princesden

1

逐个构建使用StringBuilder的查询。首先追加"select * from table1 where "。然后用plain Java编写if语句,并在每个块中添加适当的子句。