简体   繁体   中英

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;*/
    }

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;
}

Try this query:

String queryString = "SELECT " + COLUMN_USERNAME + " FROM " + ACCOUNT_TABLE + " WHERE COLUMN_USERNAME like '%" +users+”%'”;

Here COLUMN_USERNAME is your database column and Users is the string you want to search.

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