如何用rawquery编写where子句

时间:2017-10-01 05:39:34

标签: sqlite

  

嗨,我从sqlite数据库中获取数据时遇到了一些问题。我在这里取材   来自select查询的数据,但它没有响应。请帮帮我。

public ArrayList<String> getStudentsByClass(String stud_info) {
    // Log.i("SKR", "GETTING STUDENTS by " +stud_class);

        ArrayList<String> arrayList = new ArrayList<>();
    Cursor cursor = liteDatabase.rawQuery("SELECT * FROM " + DATABASE_TABLE2  +
            " WHERE ssg ='" + stud_info + "'", null);

        if (cursor != null) {
            cursor.moveToFirst();
            while (cursor.isAfterLast() == false) {
                arrayList.add(cursor.getString(cursor.getColumnIndex(KEY_STUDENT_NAME)));

                cursor.moveToNext();
            }
        }
    }
    return arrayList;
}

2 个答案:

答案 0 :(得分:0)

这是来自DBHelper类的原始查询,在调用时会填充ArrayList

    /* Retrive ALL data from database table named "TABLE_INFO" */
public List<DatabaseModel> getDataFromDB(){
    List<DatabaseModel> modelList = new ArrayList<>();

    String query = "SELECT * FROM " + TABLE_INFO;
    //String query = "SELECT * FROM " + TABLE_INFO + " WHERE " + Col_ID + " > 0 " + " ORDER BY " + Col_ID + " DESC ";
    /* Notice the SPACES before AND after the words WHERE ORDER BY ASC or DESC most of all the condition " > 0 "*/
    /* =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=*/
    db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(query,null);

    if (cursor.moveToFirst()){
        do {
            DatabaseModel model = new DatabaseModel();
            model.setID(cursor.getString(0));
            model.setWebsite(cursor.getString(1));
            model.setUsernane(cursor.getString(2));
            model.setPassword(cursor.getString(3));
            model.setQuestion(cursor.getString(4));
            model.setAnswer(cursor.getString(5));
            model.setNotes(cursor.getString(6));

            modelList.add(model);
        }while (cursor.moveToNext());
    }
    db.close();
    return modelList;
}

答案 1 :(得分:0)

使用rawQuery您可以在查询中的where子句中包含?s,它将被selectionArgs中的值替换。这些值将绑定为字符串。

    String selectQuery = "select * FROM settings where _id = ?";
    String args[] = {"1"};

    Cursor c = db.rawQuery(selectQuery, args);
    if (c.moveToFirst()) {