2012-08-08 43 views
1

我有一些字段的ORMLite数据库。我想从我从webservice获得的id == id表中选择标题。我这样做:ORMLite使用谓词选择一些列

try { 
    Dao<ProcessStatus,Integer> dao = db.getStatusDao(); 
    Log.i("status",dao.queryForAll().toString()); 
    QueryBuilder<ProcessStatus,Integer> query = dao.queryBuilder(); 
    Where where = query.where(); 
    String a = null; 
    for(Order r:LoginActivity.orders) { 
     //LoginActivity.orders - array of my objects which I get from webservice 
     Log.i("database",query.selectRaw("select title from process_status"). 
      where().rawComparison(ProcessStatus.STATUS_ID, "=", 
         r.getProcess_status().getProccessStatusId()).toString()); 
    } 
    Log.i("sr",a); 
} catch (SQLException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 

我试过这样,但我只得到我的id,而不是标题集。我试过像这样:

Log.i("database", query.selectColumns(ProcessStatus.STATUS_TITLE).where(). 
    eq(ProcessStatus.STATUS_ID, r.getProcess_status().getProccessStatusId()) 
    .toString()); 

但我有同样的结果。我应该如何从数据库中获取数据?

+0

结果是什么?例外?如果有的话,请修改您的帖子。 – Gray 2012-08-08 15:21:51

回答

14

对于从表中选择一个特定的领域,你可以做这样的事情:

String result = ""; 
try { 
    GenericRawResults<String[]> rawResults = yourDAO.queryRaw("select " + 
     ProcessStatus.STATUS_TITLE +" from YourTable where "+ 
     ProcessStatus.STATUS_ID + " = " + 
     r.getProcess_status().getProccessStatusId()); 
    List<String[]> results = rawResults.getResults(); 
    // This will select the first result (the first and maybe only row returned) 
    String[] resultArray = results.get(0); 
    //This will select the first field in the result which should be the ID 
    result = resultArray[0]; 
} catch (Exception e) { 
    e.printStackTrace(); 
} 

希望这有助于。

+0

非常感谢!这很完美! – 2012-08-09 07:40:26

+1

太棒了!您能否将其标记为已接受? – Zadec 2012-08-13 21:55:22

6

如果没有看到processStatusId字段和其他字段的所有类别,就很难正确回答这个问题。不过,我认为你正在做的太多原始方法,可能不会正确地逃脱你的价值观等。

我建议您使用IN SQL语句,而不是在循环中执行的操作。喜欢的东西:

List<String> ids = new ArrayList<String>(); 
for(Order r : LoginActivity.orders) { 
    ids.add(r.getProcess_status().getProccessStatusId()); 
} 
QueryBuilder<ProcessStatus, Integer> qb = dao.queryBuilder(); 
Where where = qb.where(); 
where.in(ProcessStatus.STATUS_ID, ids); 
qb.selectColumns(ProcessStatus.STATUS_TITLE); 

现在,您已经构建了查询,要么你可以检索你的ProcessStatus对象,也可以使用dao.queryForRaw(...)拿到冠军自己:

List<ProcessStatus> results = qb.query(); 
// or use the prepareStatementString method to get raw results 
GenericRawResults<String[]> results = dao.queryRaw(qb.prepareStatementString()); 
// each raw result would have a String[] with 1 element for the title