Reputation: 67
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;*/
}
Upvotes: 2
Views: 1675
Reputation: 164089
The proper way to do this is with the rawQuery()
method, which takes 2 arguments:
SELECT
statement with ?
placeholders for the parameters that you want to passString
array containing all the values for the parameters of the sql statement, in the order they appear in the
statementrawQuery()
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;
}
Upvotes: 1
Reputation: 92
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.
Upvotes: 0