1

我有下面的方法,它将接受两个参数-

final String userId- Primary Key for the database

final Collection<String> attributeNames- list of column names that I want to retrieve

下面是代码

public Map<String, String> getAttributes(final String userId, final Collection<String> attributeNames) {

     //Below line doesn't works out the way I wanted
     String query="SELECT" +attributeNames.toString()+ ", * from test where id = "+userId+ ";";
     ResultSet result = CassandraDatastaxConnection.getInstance().getSession().execute(query);
     for (Row rows: result){
         System.out.println(rows.getString("key"));
     } 

    return attributes;
}

举个例子,userId as 40

样品attributeNames看起来像这样 -

[account, behavior, segmentation]

现在我需要生成与输入对应的 SQL。所以对于上面的例子,sql应该是这样的——

SELECT account, behavior, segmentation from test where id = "40";

如何从上述输入生成这样的 SQL?谢谢您的帮助。

4

2 回答 2

1

你可以使用类似的东西attributeNames.toString().substring(1, attributeNames.toString().length()-1)

于 2013-04-21T02:07:27.620 回答
0

更改此功能

public Map<String, String> getAttributes(final String userId, final Collection<String> attributeNames) {
 //Below line doesn't works out the way I wanted
 String query="SELECT" +attributeNames.toString()+ ", * from test where id = "+userId+ ";";
 ResultSet result = CassandraDatastaxConnection.getInstance().getSession().execute(query);
 for (Row rows: result){
     System.out.println(rows.getString("key"));
 } 

return attributes;
}

对此

public Map<String, String> getAttributes(final String userId, final Collection<String> attributeNames) {

 //Below line doesn't works out the way I wanted
 StringBuilder sb = new StringBuilder(attributeNames.size());

 for(int i = 0; i<attributeNames.size();i++)
 {
     sb.append(attributeNames.get(i));
     if(i != attributeNames.size() - 1)
          sb.append(",");
 }
 String query="SELECT" +sb.toString()+ " from test where id = "+userId+ ";";
 ResultSet result = CassandraDatastaxConnection.getInstance().getSession().execute(query);
 for (Row rows: result){
     System.out.println(rows.getString("key"));
 } 

return attributes;
}

修改后的函数通过属性名称循环运行,并将查询部分构造为 name1、name2、name3 等,然后将其添加到查询正文中。希望这能解决您的问题。

于 2013-04-21T02:27:58.323 回答