如果值为零或0,则Android Sqlite选择Query

时间:2018-04-06 21:31:39

标签: java android sqlite

我正在尝试编写一个获取查询,如果值为:

将显示来自COURSE表的数据
course_id=0
or
semester_id=0
or
level_id=0
or
level_code=Select level
or
grade=Grade

因此,应显示具有上述任何值的任何行:

public List<Courses> getListCourseError() {
    Courses courses = null;
    List<Courses> coursesList = new ArrayList<>();
    openDatabase();
    Cursor cursor = mDatabase.rawQuery("SELECT * FROM COURSES WHERE semester_id=0 OR level_id=0 OR level_code=Select level OR grade=Grade", null);
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        courses = new Courses(cursor.getInt(0), cursor.getInt(1), cursor.getString(2), cursor.getInt(3), cursor.getInt(4), cursor.getString(5), cursor.getInt(6), cursor.getString(7), cursor.getInt(8), cursor.getInt(9));
        coursesList.add(courses);
        cursor.moveToNext();
    }
    cursor.close();
    closeDatabase();
    return coursesList;
}

由于

1 个答案:

答案 0 :(得分:0)

我相信你发出的是字符串值必须用引号括起来。你也不包括course_id是0。

而不是"SELECT * FROM COURSES WHERE semester_id=0 OR level_id=0 OR level_code=Select level OR grade=Grade"

使用: -

"SELECT * FROM COURSES WHERE course_id=0 OR semester_id=0 OR level_id=0 OR level_code='Select level' OR grade='Grade'"

但是上面是SQL注入的候选者,所以你应该使用选择args(第二个参数),这将代表你正确地包含字符串。因此,使用更正确的解决方案: -

String[] selectionargs = new String[]{"0","0","0","Select level", "Grade"};
Cursor cursor = mDatabase.rawQuery("SELECT * FROM COURSES WHERE course_id=? semester_id=? OR level_id=? OR level_code=? OR grade=?", selectionargs);

但是,建议仅在需要时使用rawQuery方法,并使用常规query方法。这将是: -

String whereclause = "course_id=? OR semester_id=? OR level_id=? OR level_code=? or grade=?";
String[] whereargs = new String[]{"0","0","0","Select level", "Grade"};
Cursor cursor = mDatabase.query(
    "COURSES",
    null, //<<<< all columns (else String[] of columns)
    whereclause, //<<<< WHERE clause without the WHERE keyword
    whereargs, //<<<< arguments to replace ?'s 
    null, //<<<< GROUP BY clause
    null, //<<<< HAVING clause
    null //<<<< ORDER BY clause   
);

备注 - null导致相应参数被忽略/默认(表名不能为空)。例如列(第二个参数)为null默认为所有列,即 *

  • 有许多不同的查询方法签名。请参阅SQLiteDatabase

  • 上面的代码是原则上的代码,尚未经过测试,因此可能会出现一些错误。