Search code examples
javaandroidsqlsqliteandroid-sqlite

Search for a specific string in an SQLite database - Android SDK


I'm using an SQLite database in Android SDK and I know this is a very simple question but I have the following function below. I'm trying to search for if a username is within the SQL database but I cant think of how I would structure the query.

What would be the proper way to search for the if the string "user" is within the table "ACCOUNT_TABLE"

public boolean isUser(String user){
        SQLiteDatabase db = this.getReadableDatabase();
        String queryString = "SELECT " + COLUMN_USERNAME + " FROM " + ACCOUNT_TABLE + " WHERE " (???);

        db.close();
        /*if(found in database) 
            return true;
        else 
            return false;*/
    }

Solution

  • The proper way to do this is with the rawQuery() method, which takes 2 arguments:

    1. the sql SELECT statement with ? placeholders for the parameters that you want to pass
    2. a String array containing all the values for the parameters of the sql statement, in the order they appear in the statement

    rawQuery() returns a Cursor which you can check if it contains any rows and if it does this means that the user you search for exists in the table:

    public boolean isUser(String user) {
        SQLiteDatabase db = this.getReadableDatabase();
        String queryString = "SELECT 1 FROM " + ACCOUNT_TABLE + " WHERE " + COLUMN_USERNAME + " = ?";
        Cursor c = db.rawQuery(queryString, new String[]{user});
        boolean result = c.getCount() > 0;
        c.close();
        db.close();
        return result;
    }