SQLITE Selection and order by causing errors - android

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".

Related

syntax error in "SELECT DISTINCT _id near "SELECT"

If someone knows a better way to get a rowId from text in the row, please let me know.
I've been running around in circles with this and I know it's probably something simple, but I can't figure it out. Hoping someone can tell me what I'm doing wrong. I'm getting an error running this SQLite code:
String where = "SELECT rowid, * FROM masterRecord WHERE masNameCol=" + name;
Cursor c = db.query(true, masterName, ALL_KEYS_MASTER, where, null, null, null, null, null);
The error points to the second line.
"name" is a string variable (in this case it's "Mary"). The exact error I'm getting is:
SQLiteLog: (1) near "SELECT": syntax error in "SELECT DISTINCT _id, masNameCol, masTotalTimeCol FROM masterRecord WHERE SELECT rowid, * FROM masterRecord WHERE masNameCol=Mary"
I've tried every syntax change I could find and think of, and it never changes the error. I'm just trying to get the rowId of the row so I can change a value in another column.
Use rawQuery(), not query().
You are trying to specify the entire SQL statement, which is what rawQuery() is for. query() assembles the SQL statement from pieces, and your one piece (where) is not just the WHERE clause.
Use placeholders for queries:
where = "masNameCol = ?";
whereArgs = new String[] { name };
columns = new String[] { "rowId" , /* all other column names you are interested in */ };
Cursor c = db.query("mytable", columns, where, whereArgs, null, null, null);

Querying sqlite in android

I'm creating a database for my game, everything is working until I want to query one item.
I have been trying few different methods and I can't make it work. I just simply don't see the error in my code.
The code is as follows:
public Item getItem(String icon) {
String[] columns = {KEY_ID, KEY_TYPE, KEY_ICON, KEY_LEVEL, KEY_ARMOR, KEY_DAMAGE, KEY_BUY, KEY_SELL};
Cursor cursor = db.query(DB_TABLE, columns, KEY_ICON + "=" + icon,
null, null, null, null);
Item item=null;
if(cursor != null && cursor.moveToFirst()) {
item= new Item(cursor.getString(TYPE_COLUMN),
cursor.getString(ICON_COLUMN),
cursor.getString(LEVEL_COLUMN),
cursor.getString(ARMOR_COLUMN),
cursor.getString(DAMAGE_COLUMN),
cursor.getString(BUY_COLUMN),
cursor.getString(SELL_COLUMN)
);
}
return item;
}
The error I'm getting is
No such column: fast_boots (code 1): while compiling: SELECT id, type,
icon, level, armor, damage, buy, sell from items where icon=fast_boots
When trying to find .getItem("fast_boots"); I do see the fast_boots in my sql database
To make the query work, maybe you should try this :
KEY_ICON + "= '" + icon + "' "
As 'icon' is a string value. Since you're not specifying it, it is probably trying to understand it as being a column in the projection
This is the wrong way of implementing such functionality, though. Do not perform database queries on the getItem() method itself (main thread), it deserves to run in background, so it won't affect the main thread.
Please read about AsyncTask.
Try this
Cursor cursor = db.query(DB_TABLE, columns, KEY_ICON + "='" + icon +"'",
null, null, null, null);
I added '

Android- SQLite query to Order Results by Day using the query builder

At the moment i'm currently using the query builder to pull all my records from my database and they are currently organised by day however I its sorts in althabetical order,
public Cursor fetchAll() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_MODULECODE,
KEY_DAY, KEY_TIME, KEY_DURATION, KEY_TYPE, KEY_ROOM},null, null, null, null,"Day");
}
I know after some googling, that I need to replace the final section with a custom search order.
something along the lines of :
select _id, busnum,
case cast (strftime('%w', servdate) as integer)
when 0 then 'Sunday'
when 1 then 'Monday'
when 2 then 'Tuesday'
when 3 then 'Wednesday'
when 4 then 'Thursday'
when 5 then 'Friday'
else 'Saturday' end as servdayofweek
from tb1
where ...
From:
http://stackoverflow.com/questions/4319302/sqlite-return-as-day-of-week
so far i have been unable to figure out how tocombine the two and anyhelp in the right direction would be much aprechiated.
Edit Soloution
thank you for the help I went with declaring the string and linking to it in the query for anyone that needs something simple this is my final code for it
public Cursor fetchAll() {
String OrderBy ="case Day"+
" when 'Monday' then 0 "+
" when 'Tuesday' then 1"+
" when 'Wednesday' then 2"+
" when 'Thursday' then 3"+
" when 'Friday' then 5"+
" end";
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_MODULECODE,
KEY_DAY, KEY_TIME, KEY_DURATION, KEY_TYPE, KEY_ROOM},null, null, null, null,OrderBy );
}
If your Day values are the day names then you want something like this:
order by case Day
when 'Sunday' then 0
when 'Monday' then 1
when 'Tuesday' then 2
...
when 'Saturday' then 6
end
in the SQL; keep in mind that you can hand an SQL ORDER BY pretty much any expression. The orderBy argument to query can be any SQL ORDER BY clause (without the order by) so you want this big ugly string :
"case Day when 'Sunday' then 0 when 'Monday' then 1 ... when 'Saturday' then 6 end"
as the last argument to query. You'll have to properly fill in the ... of course.
If you cannot figure out how to pass a complex query through SQLiteDatabase.query(... lots of variables...) just pass your select statement as a string with SQLiteDatabase.rawQuery().
For example:
String query = "select _id, busnum, " +
" case cast cast (strftime('%w', servdate) as integer) " +
...
String[] selectionArgs = new String() { yada, yada, yada }
mDb.rawQuery(query, selectionArgs);

Android SQLite Repeated Elements

I have an issue with SQLite on android. Right now, I'm pulling a JSON object from a server, parsing it, and putting each sub-object in a Table with things such as the Name, Row_ID, unique ID, etc. using this code:
public void fillTable(Object[] detailedList){
for(int i=0;i<detailedList.length;++i){
Log.w("MyApp", "Creating Entry: " + Integer.toString(i));
String[] article = (String[]) detailedList[i];
createEntry(article[0], article[1], article[2], article[3], article[4], article[5]);
}
}
createEntry does what it sounds like. It takes 6 strings, and uses cv.put to make an entry. No problems.
When I try to order them however, via:
public String[] getAllTitles(int m){
Log.w("MyApp", "getTitle1");
String[] columns = new String[]{KEY_ROWID, KEY_URLID, KEY_URL, KEY_TITLE, KEY_TIME, KEY_TAGS, KEY_STATE};
Log.w("MyApp", "getTitle2");
Cursor c = ourDatabase.query(DATABASE_TABLENAME, columns, null, null, null, null, KEY_TIME);
Log.w("MyApp", "getTitle3");
String title[] = new String[m];
Log.w("MyApp", "getTitle4");
int i = 0;
int rowTitle = c.getColumnIndex(KEY_TITLE);
Log.w("MyApp", "getTitle5");
for(c.moveToFirst();i<m;c.moveToNext()){
title[i++] = c.getString(rowTitle);
Log.w("MyApp", "getTitle " + Integer.toString(i));
}
return title;
}
Each entry actually has many duplicates. I'm assuming as many duplicates as times I have synced. Is there any way to manually call the onUpgrade method, which drops the table and creates a new one, or a better way to clear out duplicates?
Secondary question, is there any way to order by reverse? I'm ordering by time now, and the oldest added entries are first (smallest number). Is there a reverse to that?
If you don't want duplicates in one column then create that column with the UNIQUE keyword. Your database will then check that you don't insert duplicates and you can even specify what should happen in that case. I guess this would be good for you:
CREATE TABLE mytable (
_id INTEGER PRIMARY KEY AUTOINCREMENT,
theone TEXT UNIQUE ON CONFLICT REPLACE
)
If you insert something into that table that already exists it will delete the row that already has that item and inserts your new row then. That also means that the replaced row gets a new _id (because _id is set to automatically grow - you must not insert that id yourself or it will not work)
Your second question: you can specify the direction of the order of if you append ASC (ascending) or DESC (descending). You want DESC probably.
Cursor c = ourDatabase.query(DATABASE_TABLENAME, columns, null, null, null, null, KEY_TIME + " DESC");

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

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.

Categories

Resources