简体   繁体   中英

How to retrieve the result of a select query in Sqlite java android?

I'm looking to retrieve the result of my request in variables to be able to check if the authentication is correct. In simple sql it does this with a Resultset but I understood that in Sqlite you have to use a Cursor. But I can't get a result. Here are two examples of what I have already tried :

    public boolean checkAuthentication(String login, String password){

        boolean check = false;

        SQLiteDatabase db = dbManager.getWritableDatabase();
        SQLiteStatement statement = db.compileStatement("SELECT * from Visiteur WHERE vis_login = ? and vis_mdp = ?");
        statement.bindString(1, login);
        statement.bindString(2, password);
        //statement.execute();
        return check;

    }

    public boolean checkAuthentication2(String login, String password){

        boolean check = false;
        String log = null;
        String pass = null;

        String sql = "SELECT * from Visiteur WHERE vis_login = ? and vis_mdp = ?";
        SQLiteStatement statement = db.compileStatement(sql);
        statement.bindString(1, login);
        statement.bindString(2, password);

        Cursor cursor = db.rawQuery(sql, null);

        while(cursor.moveToNext()){
            log =  cursor.getString(cursor.getColumnIndex("vis_login"));
            pass = cursor.getString(cursor.getColumnIndex("vis_mdp"));
            Log.d("WHILE", log);
        }
        cursor.close();
        statement.close();

        if(log != null && pass != null){
            check = true;
        }


        return check;

    }

Thanks for responses.

Use rawQuery() method to get a Cursor on which you don't have to iterate.
Just check if 1 row is returned because this is what you want to know: if a user exists with the specific login and password :

public boolean checkAuthentication(String login, String password){
    boolean check = false;
    String sql = "SELECT * from Visiteur WHERE vis_login = ? and vis_mdp = ?";
    SQLiteDatabase db = dbManager.getWritableDatabase();
    Cursor cursor = db.rawQuery(sql, new String[] {login, password});
    check = cursor.moveToFirst();
    cursor.close();
    db.close();
    return check;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM