ANDROID: Can I do SELECT with WHERE clause as String? - android

So I have data in my database & the value of category is set to "Breakfast"
When I execute the below Query with whereClause as
1:final String whereClause = RECIPE_ID + "=1";
It returns me the data for that RECIPE_ID
But when I execute the query with whereClause as
2:final String whereClause = RECIPE_CATEGORY + "='" + category.trim() + "'";
It doesn't return anything... So I guess my code is working fine as it returns result
RECIPE_ID but I donno why it doesn't return data for the 2nd whereClause
Hope this makes sense..
final String whereClause = RECIPE_CATEGORY + "='" + category.trim() + "'";
// ask the database object to create the cursor.
cursor = db.query(
RECIPE_TABLE,
new String[]{
RECIPE_ID,
RECIPE_CATEGORY,
RECIPE_THIS_TITLE,
RECIPE_THIS_SUBTITLE,
RECIPE_THIS_DESCRIPTION,
RECIPE_THIS_IMAGE,
RECIPE_THIS_CALORIES,
RECIPE_THIS_FAT,
RECIPE_THIS_SATURATED,
RECIPE_THIS_TRANS,
RECIPE_THIS_CARBS,
RECIPE_THIS_SODIUM,
RECIPE_THIS_SUGARS,
RECIPE_THIS_SERVINGS,
RECIPE_THIS_COSTPERSERVING,
RECIPE_THIS_INSTRUCTIONS,
RECIPE_THAT_TITLE,
RECIPE_THAT_CALORIES,
RECIPE_THAT_FAT,
RECIPE_THAT_SATURATED,
RECIPE_THAT_TRANS,
RECIPE_THAT_CARBS,
RECIPE_THAT_SODIUM,
RECIPE_THAT_SUGARS,
RECIPE_THAT_PRICE
},
whereClause, null, null, null, null
);
The above code will not return any results. Is anything wrong with it?

You really need to form a question here. Posting code does you no good. If your question is as you title implies, then yes you can do a search clause as a string. Just leave out the where. eg dataId = 5 where 'where' is implied.
Edit: to address the question at the bottom that I missed, multiple things could be wrong. One may be that you dont have any data in the database. Or the where clause is executed and none of your data fits the criteria. Check your database. We can't help with that.

Related

Android: Getting row by id

I'm trying to get database row by it's ID, but somehow query doesn't return that row. The sql query SELECT * From Table1 Where _id = 100 works good, so I don't know what's the reason. Here is the code of the query:
String [] selectedArgs = new String [] {String.valueOf(selectedItemId)};
String selection = Tables.Table1.COLUMN_ID + "=?";
String [] columns = {Tables.Table1.COLUMN_ID, Tables.Table1.COLUMN_NAME};
Cursor c = foodDB.query(Tables.Food.TABLE_NAME, columns, selection, selectedArgs, null, null, null);
Does anybody have any suggestions?
The problem is that your ID field is a number, while the parameter is a string; the query function does not allow other parameter types for some strange reason.
Try using an expression like COLUMN_ID + " = CAST(? AS INTEGER)".
If your query had only one result column, you could use a separate SQLiteStatement object where you'd be able to use bindLong().
Just in case somebody need it, i have used rawQuery() method for such type of query to work, because query() doesn't work.

SQLite Database Problem while delete

Hi to All I am new to Android.
I am using SQLite DataBase in my Application
meanwhile I am Written Queries using +
Like delete from tablename where value = + value;
this is my query
String delete_query = "delete from " + tableName
+ " where title = '" + title + "'";
database.execSQL(delete_query);
I want to write this Query using placeholder ?.
so that i tried
database.delete(tableName, title + "?" , new String[] {title});
instead "?" i tried (?)/('?')/'?'
but it is giving me an error....
can any one tell me how to write appropriate query using ?.....
Thanks in Advance.
Mahaveer
Make sure you have put the equal sign:-
database.delete(tableName, title + "=?" , new String[] {title});
As far as possible, try to use the less raw queries you can. Two advantages:
Query parameters will be escaped by the system (protection against SQL injection)
The code will be more readable
See the delete function of SQLiteDatabase class
public int delete (String table, String whereClause, String[]
whereArgs)
Convenience method for deleting rows in the
database.
table the table to delete from
whereClause the optional WHERE clause
to apply when deleting. Passing null will delete all rows.
Returns the number of rows affected if a whereClause is passed in, 0
otherwise. To remove all rows and get a count pass "1" as the
whereClause.
In your case:
final String where = "title=?";
final String[] args = new String[] { title };
database.delete(tableName, where, args);

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

Android SQLite strange issue

In my app I have one DB table with that structure:
user TEXT | token text
When I'm doing request to check if this user exist in table, like that:
String whereClause = COLUMN_USER + "==\"" + userName + "\"";
Cursor c = db.query(TABLE_USERS, new String[]{COLUMN_USER, COLUMN_TOKEN}, whereClause, null, null, null, null);
It works for all users. But if variable userName is "user" I got all records back.
Looks like sqllite checks table structure, and return to me all records 'cos name of this column equals to my value that I'm using - user.
I suggest you parameterize the arguments in your where clause:
String whereClause = COLUMN_USER + "=?";
String [] whereArgs = { userName };
Cursor c = db.query(TABLE_USERS, new String[]{COLUMN_USER, COLUMN_TOKEN}, whereClause, whereArgs, null, null, null);
A simple kludge to get rid of this problem would be simply to enclose the query in:
if (userName =! "user") {
//code here
} else {
//open dialog about invalid username
}
Although i'm sure there's a more elegant solution. Input Data sanitizing should be done anyways, and if you're already checking for invalids, maybe just add "user" into the list of rejecteds?

SQLITE Selection and order by causing errors

i'm trying to get a query that returns rows only with a specified name, and sort descending by week (integer).
Everytime I try and run it it gives me a FC and logcat says
ERROR/AndroidRuntime(728): android.database.sqlite.SQLiteException: no such column: New: , while compiling: SELECT Name, Week, Total FROM notes WHERE Name=New ORDER BY WeekDESC LIMIT 10
public Cursor graphQuery(String name){
return mDb.query(DATABASE_TABLE, new String[] {KEY_NAME,
KEY_WEEK, KEY_TOTAL}, KEY_NAME + "=" + name, null, null, null, KEY_WEEK + "DESC","10");
}
It says that there is no such column, which doesn't make sense because it should be looking at the names in the row and returning the ones that match. Also if I put KEY_NAME + "=" + name as null, it says that there is no such column WeekDESC which doesn't make sense either cause it is just supposed to be sorting by an integer.
I have gotten this code working before, but I misplaced it and can't seem to get it working again... This is getting frustrating, any help is very much appreciated!
If you search by string, you should use a question mark as a placeholder, i.e.
return mDb.query(DATABASE_TABLE, new String[] {KEY_NAME,
KEY_WEEK, KEY_TOTAL}, KEY_NAME + "=?", new String[] { name }, null, null, null, KEY_WEEK + "DESC","10");
Or else it will break if the name contains spaces or special characters.
(If you really don't want to you the question mark, you need to put the string in quotes or double-quotes, but using a question mark is far more elegant and safe.)
Also: There is no space between "DESC" and the key you're sorting by. Use " DESC".

Categories

Resources