2012-08-08 65 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