使用 Java 中的布尔值检查数据库中是否存在值

Check if value exist in DB with Boolean in Java

我想做的是检查 'profiles' table 上的 profilePicture 列中是否有任何数据,如果没有数据,getCount 将 return 0 并且应该 return 错误。如何进行查询以仅获取 profilePicture 列中的数据以查看用户 ID 是否为 null。

public Boolean checkProfilePicture(String user_id){
        SQLiteDatabase MyDB = this.getReadableDatabase();

        Cursor cursor = MyDB.rawQuery("Select * from profiles where ID = ? and profilePicture = NULL", new String[] {user_id});
        System.out.println(cursor.getCount());

        if (cursor.getCount() > 0)
            return true;
        else
            return false;
    }

您的查询应该 return 只有 1 列,它是 1 (true) 或 0 (false) 形式的布尔值,为此您必须使用表达式喜欢:

profilePicture IS NOT NULL

您必须使用运算符 ISIS NOTNULL 进行比较,而不是使用 =<>!=

public boolean checkProfilePicture(String user_id){
    SQLiteDatabase MyDB = this.getReadableDatabase();
    Cursor cursor = MyDB.rawQuery("SELECT profilePicture IS NOT NULL FROM profiles WHERE ID = ?", new String[] {user_id});
    boolean result = cursor.moveToFirst();
    if (result) result = (cursor.getInt(0) == 1) ;
    cursor.close();
    MyDB.close();
    return result;
}