ORMLite使用谓词选择一些列

时间:2012-08-08 14:08:50

标签: android select where ormlite

我有一些字段的ORMLite数据库。我想从表中选择我从webservice获得的id == id的标题。我喜欢这样:

 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();
}

我试过这样但我只得到了我的身份证,而不是头衔。我试过这样:

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

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

2 个答案:

答案 0 :(得分: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();
}

希望这有帮助。

答案 1 :(得分: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