当给 args 赋空值时,RawQuery 不起作用

RawQuery doesn't work when given null valueto args

我正在编写一个基本的 android 应用程序,其中通过按 "submit" 按钮(这一切工作完美)。然后有一个搜索按钮,当一个字段被填写时,它应该在数据库中搜索对应的人(例如,只有字段名称被赋予一个字符串 "harry" 并且其他字段保持空值)。这是我的DatabaseHelper中对应的代码class:

public Person getPerson(String naam, String adres, String email, String geslacht,
        String leeftijd, String geboortedatum){
    Log.i("Main activity","Person to find: "+naam);
    SQLiteDatabase db= this.getReadableDatabase();
    Cursor curs=db.rawQuery("SELECT name FROM personen WHERE (name = ?) OR (adress = ?) "
            + "OR (email = ?) OR (gender = ?) OR (age = ?) OR (birthday = ?)", 
            new String[]{naam, adres, email, geslacht, leeftijd, geboortedatum});
    Log.i("Main activity", "Query works");

我使用日志来确定错误发生的位置,并发现当所有 args[] 字段都被赋予一个值时 rawQuery 确实有效,但当一个字段(例如电子邮件)包含 null 时会出错价值。这难道不是我应该使用 OR 语句而不是 AND 语句的原因吗?如果没有,当应用程序中没有填写所有字段时,我如何才能让它工作?

一个快速的解决方法应该是做这样的事情:

new String[]{naam == null? "''":naam, etc}

检查您的 sting 是否已初始化,如果未初始化,请将其替换为虚拟值。

按名称搜索:

// Getting single contact 
Contact getContact(String name) {
SQLiteDatabase db = this.getReadableDatabase();

Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
        KEY_NAME, KEY_PH_NUM }, KEY_NAME + "=?",
        new String[] { name }, null, null, null, null);
//...

访问权限:

Contact contact = null;
if (cursor.moveToFirst()) {
contact = new Contact(Integer.parseInt(cursor.getString(0)),
        cursor.getString(1), cursor.getString(2));
}
cursor.close();
// can return null if no contact was found.
return contact;

rawQuery() 需要一个字符串数组,但 null 不是有效的字符串。

您必须将 NULL 直接放入 SQL 字符串中,不带参数。 但是无论如何,当您动态构造字符串时,您也可以省略该比较。