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);
Related
My app queries a particular event in CalendarContract.Events using Events._ID. This worked well until attempting to run it on a 5.0 device, now I get an exception
01-12 17:28:50.525: E/Unknown Source(18499): android.database.sqlite.SQLiteException:
no such column: CalendarContract.Events._ID (code 1): ,
while compiling:
SELECT _id, account_type, title, organizer, description, eventLocation,
hasAlarm, calendar_id
FROM view_events
WHERE (lastSynced = 0 AND (CalendarContract.Events._ID=1))
Querying all columns in Events indeed does not return _ID. Any idea why this has been removed or if it's a bug? I can't seem to find away to uniquely identify events any more.
Here is my query:
String[] projection = new String[]{Events._ID, Events.ACCOUNT_TYPE, Events.TITLE,
Events.ORGANIZER, Events.DESCRIPTION, Events.EVENT_LOCATION, Events.HAS_ALARM,
Events.CALENDAR_ID};
Cursor cursor = context.getContentResolver().query(EVENTS_CONTENT_URI, projection,
"CalendarContract.Events._ID=" + eventId, null, null);
Thanks for any information!
The answer of #Andrew isn't right.
You are wrongly using the selectionClause and the selectionArgs parameters.
Here is what you are doing:
Cursor cursor = context.getContentResolver().query(EVENTS_CONTENT_URI, projection,
CalendarContract.Events._ID + "=" + eventId, null, null);
And here is what you should do:
Cursor cursor = context.getContentResolver().query(EVENTS_CONTENT_URI, projection,
CalendarContract.Events._ID + " = ?", new String[]{eventId}, null);
The eventId needs to be passed within the selectionArgs so that the contentResolver can build the query statement for you, chaining the selectionArgs and substituting them to the ? char in the selectionClause parameter.
The question is three years old, but I hope my answer can help someone else.
I'm writing a method to update default settings in a table. The table is very simple: two columns, the first containing labels to indicate the type of setting, the second to store the value of the setting.
At this point in the execution, the table is empty. I'm just setting up the initial value. So, I expect that this cursor will come back empty. But instead, I'm getting an error (shown below). The setting that I am working with is called "lastPlayer" and is supposed to get stored in the "SETTING_COLUMN" in the "SETTINGS_TABLE". Here's the code:
public static void updateSetting(String setting, String newVal) {
String table = "SETTINGS_TABLE";
String[] resultColumn = new String[] {VALUE_COLUMN};
String where = SETTING_COLUMN + "=" + setting;
System.err.println(where);
SQLiteDatabase db = godSimDBOpenHelper.getWritableDatabase();
Cursor cursor = db.query(table, resultColumn, where, null, null, null, null);
System.err.println("cursor returned"); //I never see this ouput
\\more
}
sqlite returned: error code = 1, msg = no such column: lastPlayer
Why is it saying that there is no such column lastPlayer? I thought that I was telling the query to look at the column "SETTING_COLUMN" and return the record where that column has a value "lastPlayer". I'm confused. Can somebody straighten me out? I've been looking a this for an hour and I just don't see what I am doing wrong.
Thanks!
You're not properly building/escaping your query. Since the value lastPlayer is not in quotes, your statement is checking for equality of two columns, which is what that error message is saying.
To properly build your query, it's best to not do this manually with String concatenation. Instead, the parameter selectionArgs of SQLiteDatabase.query() is meant to do this.
The parameters in your query should be defined as ? and then filled in based on the selectionArgs. From the docs:
You may include ?s in selection, which will be replaced by the values
from selectionArgs, in order that they appear in the selection. The
values will be bound as Strings.
So, your code would look like this:
String where = SETTING_COLUMN + " = ?";
Cursor cursor = db.query(table, resultColumn, where, new String[] { setting }, null, null, null);
I was trying to solve the question on why I was getting this error yesterday with some code:
java.lang.IllegalArgumentException: column '_id' does not exist
I had a lot more code, especially that I did not need, so I stripped a lot of it out to make it easier to understand where I am going wrong. But essentially this is my schema:
database.execSQL("CREATE TABLE events (" +
"_id INTEGER PRIMARY KEY, event_name TEXT" +
")");
As one can tell, looks fine right.
Unless I forgot to read, it's most obviously there. But then I figured out where my error was coming from, or at least I am sure this is why. This code that retrieves a cursor:
public Cursor getEventsName() {
return database.rawQuery( "SELECT event_name FROM events", null);
}
According to android, this is the error. When I change it to this:
public Cursor getEventsName() {
return database.rawQuery( "SELECT * FROM events", null);
}
Everything is peachy. When the former, it crashes. Any reason as to why this is. I thought that in rawQuery() I could do that. So long as I am not including where clauses, which I am not. Any help much appreciated.
Let's call these, event cursor:
public Cursor getEventsName() {
return database.rawQuery( "SELECT event_name FROM events", null);
}
... and * cursor:
public Cursor getEventsName() {
return database.rawQuery( "SELECT * FROM events", null);
}
Most of the answers that you have received (even the ones here: In Android, does _id have to be present in any table created?) are guessing at the likely cause for your error. I figured I would answer your question as well:
Any reason as to why (the former crashes and the later is peachy?)
The difference between the * and event cursors is that * is selecting every column implicitly and event is only selecting event_name. In your events table, the * cursor is the equivalent of:
SELECT _id, event_name FROM events;
which is why the this cursor works just peachily. In other words you are not receiving this error:
java.lang.IllegalArgumentException: column '_id' does not exist
because you are implicitly selecting the _id column with *.
Of course the most probable reason for getting this error is when you bind your data with a ListView, Spinner, etc; they all tend to use a CursorAdapter of some form. This is from the CursorAdapter documentation:
Adapter that exposes data from a Cursor to a ListView widget. The Cursor must include a column named "_id" or this class will not work.
So the Solution is simple: you must select the _id column in your query as well as the other columns that you want. (The compiler isn't lying to you.)
That being said, if this still doesn't seem valid to your app or doesn't make sense please post the code where you use the Cursor and the error is thrown.
I suspect that whatever was handling the cursor was trying to get the _ID column but it wasn't specified in your select statement. Doing something like,
public Cursor getEventsName() {
return database.rawQuery( "SELECT _id, event_name FROM events", null);
}
Some Android components, such as the SimpleCursorAdapter require the _ID be available in the select statement since it uses internally when getItemId() is called.
java.lang.IllegalArgumentException: column '_id' does not exist
I had same problem, this exception is thrown because SimpleCursorAdapter need for SELECT column named _id so you can resolve it when for example if you created some table with column KEY_ID as PK so you can try it like this:
SELECT KEY_ID AS _id, column1, column2 FROM SomeTable.
public Cursor getEventsName() {
return database.rawQuery( "SELECT * FROM events", null);
Change it to
public Cursor getEventsName(){
final String[] columns = new String[]{"_id", "event_name "};
return database.query(events, columns, "" , null, null, null, null);
}
I have variable:
String owner="Mike";
String[] columns ={"quantity", "price","owner"}
My cursor is trying to get
Cursor findEntry = db.query("sku_table", columns, "owner="+owner, null, null, null, null);
I got an error no such column error
android.database.sqlite.SQLiteException: no such column: owner: , while compiling: SELECT quantity, price, owner, FROM sku_table WHERE owner=Mike
But if I take this query:
SELECT quantity, price, owner, FROM sku_table WHERE owner=Mike
and add "" to Mike, and tested in sqlite browsers to execute the query, I do get back the row.
The working query looks like this:
SELECT quantity, price, owner, FROM sku_table WHERE owner="Mike"
Can somebody drop some insights about how do I incorporate double quotes? Other than use \"
Thanks!
Sorry, but that is exactly the reason why you should work with what the method offers! #Leandros and #Jake are helping in the totally wrong direction! Sorry to say that...
The only solution you should use is this:
Cursor findEntry = db.query("sku_table", columns, "owner=?", new String[] { owner }, null, null, null);
ps: Yes I down voted both answers as they may work but providing a solution that shouldn't be used.
Update:
If you need more than one where condition, just add it like you would do in a normal query
Cursor findEntry = db.query("sku_table", columns, "owner=? and price=?", new String[] { owner, price }, null, null, null);
The order of the ? and the new String[] {...} elements must be the same!
Cursor findEntry = db.query("sku_table", columns, "owner='"+owner+"'", null, null, null, null);
SELECT quantity, price, owner, FROM sku_table WHERE owner='Mike' this is the correct SELECT. You forget the ' ' (single quotes)
public Cursor show_vol(String vol,String bk,String hadnu)
{
SQLiteDatabase db = this.getReadableDatabase();
String[] columns ={"hadith"};//colums name that you select
Cursor res = db.query("volume2", columns, "hadithno=?", new String[] { hadnu }, null, null, null);
//volume2 is table name and hadithno is colume name l
//select hadith from volume2 where hadithno=hadnu //working like s
1. List item
return res;
}
I know this is an old question, but you can also do it like this:
Cursor findEntry = db.query("sku_table", columns, "owner=\'"+owner+"\'", null, null, null, null);
I just did it in my app and it worked as expected.
Jake's answer was similar, but probably wouldn't work without the \ before the '
the simplest way is to use SELECT col1,col2 FROM table_name WHERE col =' something' ; just like Leandros said , my problem was the single quotes , thnx
I'm getting an annoying error when trying to query some data in SQLite.
Here is my code:
Cursor cursor= db.query(TABLE_IMAGES, new String[]{"_id"}, "name" +" = "+compareToThis, null, null, null, null);
I'm just returning the cursor as a string.
The error is saying:
no such column: compareToThis: while compiling.....the statement
My question is: why is SQLite setting the compareToThis attribute as a column when it's just a value?
How can I fix this?
Thanks in advance.
Cursor cursor= db.query(TABLE_IMAGES, new String[]{"_id"}, "name" +" = ?", new String[]{compareToThis}, null, null, null);
The selection must include placeholder for parameter, and the next argument should be the array of parameters.
The solution by Vladimir works, however if you are like me and wonder why your approach did not work initially when it should have, here is why:
It is because it expects an integer unless you used (single or double) quotation marks to indicate that it is a string.
For example, in MySql this would return no results:
SELECT * FROM clients WHERE firstName = Bob; -- This will not work.
However when you surround it with quotations, it will return a result because it identifies Bob as a String literal.
Select * FROM clients WHERE firstName = 'Bob'; -- Single quotes work.
Select * FROM clients WHERE firstName = "Bob"; -- Double quotes as well.
Therefore for it to work, you would have to surround your compareToString with single quotes, as Muhhammad mentioned within the comments.
Cursor cursor= db.query(TABLE_IMAGES, new String[]{"_id"}, "name" +'" = "+compareToThis+"'", null, null, null, null);