SQL using with clause not working - android

My question is why this query does not work?
Cursor c = db.rawQuery("SELECT * FROM tbl_staff WHERE PMajor = '%" + spin.getSelectedItem().toString() + "%'", null);
Cursor c: it is a cursor for handling my query
tbl_staff: my table that consist of PName, PMajor, PCert
spin: is spinner that has values which I need for my database query.
When I use:
if (c.moveToNext())
else (log.d("error query","couldn't do the query!");)
It goes to else statement and moveToNext() doesn't work.

Instead of using =, which checks for equality, use keyword LIKE, which matches a pattern.
Cursor c = db.rawQuery("SELECT * FROM tbl_staff WHERE PMajor LIKE '%" + spin.getSelectedItem().toString() + "%'", null);

Related

getContentResolver().query android where clause

My query is regarding the creation of the function parameters for getting data from the database.
I want the cursor to returns only specific rows instead of complete recordset.
c= getContentResolver().query(uri, null, "column1=? \"mysearch\" or column2=? "\mysearch"\", null, "date DESC");
I want to get the results where column1 like "mysearch" or column2 like "mysearch".
In the above example i have tried with some hardcoded values.
Regards,
Nirav
Got it after some workaround.
The correct query will be
String searchQuery = "column1 like '%" + searchKey
+ "%' or column2 like '%" + searchKey + "%'";
c = getContentResolver().query(uri, null, searchQuery, null,
"date DESC");
Thanks,
Nirav

how to use db.query() when i have many conditions in where clause?? #android

i have a table with columns ID,SUBJECT,BRANCH
i have select the rows which satisfies the follwing conditions
id=rollno
branch=cse
subject=any subject
db.query(DATABASE_TABLE, new String[] {
ID,SUBJECT,BRANCH},
where clause,
null,
null,
null,
null);
how to write where clause here to satisfy my conditions?
You can use db.rawQuery methos also
Cursor cursor= db.rawQuery("select * from <table_name> where id='1' and
branch='" + branchName + "' and subject='" + subjectName+ "'");
add Where clauses with " AND ".. Pretty simple.. Each condition is seperated by the same..
here is an example
String addrWhere = ContactsContract.Data.CONTACT_ID+" = ? AND "+ContactsContract.Data.MIMETYPE+" = ?"; //this is where clause and below is corresponding selection args..
String[] addrWhereParams = new String[]{data.getContac_ID(),
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE};

SQLite Count where query

I use a simple sql lite query to fetch the count value from a table.
Cursor cursor = db.rawQuery("SELECT sum(name2) FROM " + TABLE_NAME, null);
if (cursor.moveToFirst()) {
return cursor.getInt(0);
}
return cursor.getInt(0);
This works good
But when I add a where clause to the select query
Cursor cursor = db.rawQuery("SELECT sum(name2) FROM " + TABLE_NAME + "WHERE name in (" + k + ")", null);
if(cursor.moveToFirst()) {
return cursor.getInt(0);
}
return cursor.getInt(0);
process stops unexpectedly.......
You're missing a space in front of the WHERE: ... + TABLE_NAME + "WHERE name ...
But there's a lot wrong with your code:
Why do you use rawQuery() when there's nice methods like query(table, columns, selection, selectionArgs, groupBy, having, orderBy) that spare you from building query strings at risk of SQL injection? Even rawQuery() takes query arguments as second parameter.
Where do you close your Cursor? You'll leak memory this way.
What happens if cursor.moveToFirst() returns false and you execute the line after your if-block? This will crash.
Check the value of that k variable, it might be not valid for sql IN operator.

cant use like clause in android app

I am working on a database with sqllite in an android app
I want to retrieve sm data using a like clause
ex:
Cursor c = myDB.query(MY_DATABASE_TABLE, null, " SongName LIKE '%"+"=?"+"%'" ,
new String[]{match_str}, null, null,"SongHit DESC");
It should give all SongName starting with match_str but its not working.Why?
This:
" SongName LIKE '%"+"=?"+"%'"
Will end up looking like this when the SQL interpreter sees it:
" SongName LIKE '%=?%'"
And that will match any SongName that contains a literal "=?" and I don't think that's anything like what you want.
A % matches any sequence of characters in an SQL LIKE, it is essentially the same as .* in a regular expression; so, if you want to match at the beginning then you don't want a leading %. Also, your ? placeholder needs to be outside the single quotes or it will be interpreted as a literal question mark rather than a placeholder.
You want something more like this:
String[] a = new String[1];
a[0] = match_str + '%';
Cursor c = myDB.rawQuery("SELECT * FROM songs WHERE SongName LIKE ?", a);
If you wanted to be really strict you'd also have to escape % and _ symbols inside match_str as well but that's left as an exercise for the reader.
Try this:
String[] args = new String[1];
args[0] = "%"+song+"%";
Cursor friendLike = db.rawQuery("SELECT * FROM songs WHERE SongName like ?", args);
No need for the equal sign and you should be able to include the ? right in the string without the need for the + operator. The where clause should just be:
"SongName LIKE '%?%'"
and if mu is too short is correct and you only want starting with...
"SongName LIKE '?%'"
hi Are you getting any exception while executing the above query. Try by removing the "=" symbol infront of the question mark in the like condition. Else try using
db.rawQuery(sql, selectionArgs)
This works perfectly for me...
"Songname LIKE ? "...
cursor = database.rawQuery(query, new String[]{"%" + searchTerm + "%"});
If you wish to use query() instead of rawQuery(), you can do it like so:
// searchString is the string to search for
final String whereClause = "MyColumnName" + " like ?";
String[] whereArgs = new String[]{"%" + searchString + "%"};
Cursor cursor = sqLiteDatabase.query("MyTableName",
null, // columns
whereClause, // selection
whereArgs, // selectionArgs
null, // groupBy
null, // having
null, // orderBy
null); // limit
a simple way is to use the concatenate operator ||
"SongName LIKE '%'||?||'%'"
so there is no need to edit the match_str.
Cursor c = myDB.query(MY_DATABASE_TABLE, null, " SongName LIKE '%'||?||'%'" ,
new String[]{match_str}, null, null,"SongHit DESC");
from https://stackoverflow.com/a/46420813/908821

SQLite Query in Android to count rows

I'm trying to create a simple Login form, where I compare the login id and password entered at the login screen with that stored in the database.
I'm using the following query:
final String DATABASE_COMPARE =
"select count(*) from users where uname=" + loginname + "and pwd=" + loginpass + ");" ;
The issue is, I don't know, how can I execute the above query and store the count returned.
Here's how the database table looks like ( I've manged to create the database successfully using the execSQl method)
private static final String
DATABASE_CREATE =
"create table users (_id integer autoincrement, "
+ "name text not null, uname primary key text not null, "
+ "pwd text not null);";//+"phoneno text not null);";
Can someone kindly guide me as to how I can achieve this? If possible please provide a sample snippet to do the above task.
DatabaseUtils.queryNumEntries (since api:11) is useful alternative that negates the need for raw SQL(yay!).
SQLiteDatabase db = getReadableDatabase();
DatabaseUtils.queryNumEntries(db, "users",
"uname=? AND pwd=?", new String[] {loginname,loginpass});
#scottyab the parametrized DatabaseUtils.queryNumEntries(db, table, whereparams) exists at API 11 +, the one without the whereparams exists since API 1. The answer would have to be creating a Cursor with a db.rawQuery:
Cursor mCount= db.rawQuery("select count(*) from users where uname='" + loginname + "' and pwd='" + loginpass +"'", null);
mCount.moveToFirst();
int count= mCount.getInt(0);
mCount.close();
I also like #Dre's answer, with the parameterized query.
Use an SQLiteStatement.
e.g.
SQLiteStatement s = mDb.compileStatement( "select count(*) from users where uname='" + loginname + "' and pwd='" + loginpass + "'; " );
long count = s.simpleQueryForLong();
See rawQuery(String, String[]) and the documentation for Cursor
Your DADABASE_COMPARE SQL statement is currently invalid, loginname and loginpass won't be escaped, there is no space between loginname and the and, and you end the statement with ); instead of ; -- If you were logging in as bob with the password of password, that statement would end up as
select count(*) from users where uname=boband pwd=password);
Also, you should probably use the selectionArgs feature, instead of concatenating loginname and loginpass.
To use selectionArgs you would do something like
final String SQL_STATEMENT = "SELECT COUNT(*) FROM users WHERE uname=? AND pwd=?";
private void someMethod() {
Cursor c = db.rawQuery(SQL_STATEMENT, new String[] { loginname, loginpass });
...
}
Assuming you already have a Database (db) connection established, I think the most elegant way is to stick to the Cursor class, and do something like:
String selection = "uname = ? AND pwd = ?";
String[] selectionArgs = {loginname, loginpass};
String tableName = "YourTable";
Cursor c = db.query(tableName, null, selection, selectionArgs, null, null, null);
int result = c.getCount();
c.close();
return result;
how to get count column
final String DATABASE_COMPARE = "select count(*) from users where uname="+loginname+ "and pwd="+loginpass;
int sometotal = (int) DatabaseUtils.longForQuery(db, DATABASE_COMPARE, null);
This is the most concise and precise alternative. No need to handle cursors and their closing.
If you are using ContentProvider then you can use:
Cursor cursor = getContentResolver().query(CONTENT_URI, new String[] {"count(*)"},
uname=" + loginname + " and pwd=" + loginpass, null, null);
cursor.moveToFirst();
int count = cursor.getInt(0);
If you want to get the count of records then you have to apply the group by on some field or apply the below query.
Like
db.rawQuery("select count(field) as count_record from tablename where field =" + condition, null);
Another way would be using:
myCursor.getCount();
on a Cursor like:
Cursor myCursor = db.query(table_Name, new String[] { row_Username },
row_Username + " =? AND " + row_Password + " =?",
new String[] { entered_Password, entered_Password },
null, null, null);
If you can think of getting away from the raw query.
int nombr = 0;
Cursor cursor = sqlDatabase.rawQuery("SELECT column FROM table WHERE column = Value", null);
nombr = cursor.getCount();

Categories

Resources