I had a problem with updating of a column's value at a particular row. I had written
Cursor c = mDb.rawQuery("UPDATE "+book+" SET footnotes='" + note + "' WHERE chapter="+chapter+" and verse="+verse+"", null);
c.close();
But on adding c.moveToFirst() it worked. Why is that?
Cursor c = mDb.rawQuery("UPDATE "+book+" SET footnotes='" + note + "' WHERE chapter="+chapter+" and verse="+verse+"", null);
c.moveToFirst();
c.close();
Why is c.moveToFirst() necessary here, any particular reason?
There is an explation for c.moveToFirst()
(What is The use of moveToFirst () in SQLite Cursors) which briefly suggests that using c.moveToFirst() does two things
allows you to test whether the query returned an empty set
moves the cursor to the first result
But how does the above two things help in updation?
Think of rawQuery() as a wrapper for the C library sqlite3_prepare_v2() that compiles the SQL but does not run it, while think of moveTo..() as a wrapper for sqlite3_step() that is required for actually executing the prepared statement.
Related: What is the correct way to do inserts/updates/deletes in Android SQLiteDatabase using a query string?
Related
Hello Stackoverflow members!
There is a strange problem in my app. When there is a few db rows (more than 0) in the table, the query works good. when there is no rows in the table, the app crashes ,and then, if I remove these lines, the app works ok:
Cursor result = db.rawQuery("Select * from users ORDER BY `ID` DESC" ,null);
result.moveToFirst();
String lastuser = result.getString(resultSet2.getColumnIndex("username"));
I hope you can help me =]
It looks like the crash is caused by the result not having any rows. You can check how many rows you obtained by using the getCount method on your cursor. If it's zero, do not try to get results from an empty set.
You can read more about cursors here.
After making your query, the cursor will be before the first position. So you have to move it to the first position, as you already do it with result.moveToFirst(). However, if your result was empty, the there is no first position and you get an Exception.
What you could do is either test
if(result.moveToFirst()){
// here you can access the content
}
or you try it with a loop (that way you can also react on results with multiple rows)
while(result.moveToNext()){
String lastuser = result.getString(resultSet2.getColumnIndex("username"));
// here you can access ALL row entries one after another, or just the one row
}
Here is a clear tutorial on using SQLite – hope it helps
First change your query as(remove single quote from ID )
Cursor result = db.rawQuery("Select * from users ORDER BY ID DESC" ,null);
And as #Gooey suggest You can check how many rows you obtained by using the getCount.
So use
Cursor result = db.rawQuery("Select * from users ORDER BY ID DESC" ,null);
if ((result != null) && (result.getCount() > 0)) {
result.moveToFirst();
String lastuser = result.getString(resultSet2.getColumnIndex("username"));
}
And post logcat exception,if still problem occur.
We pass so many parameters to query() method of android. Android has simplified our work by giving query method. Is there any way so that i can print the sql query which android will form from this query method arguments which android creates and sends to sqlite.
According to a previous post, I have tried and I got the following solution in order to print the query string in the log.
Use buildQueryString method of SQLiteQueryBuilder. It takes almost same parameters as query() method takes .........
String sqlQry = SQLiteQueryBuilder.buildQueryString(false,TABLE_NAME, null, COLUMN_NAME_PATIENTID +"="+ patientID, null, null, COLUMN_NAME_PATIENTFIRSTNAME, null);
Log.i(TAG, sqlQry);
cursor = db.query(TABLE_NAME, null, COLUMN_NAME_PATIENTID +"="+ patientID, null, null, null, COLUMN_NAME_PATIENTFIRSTNAME);
For what it's worth, if you run under the debugger you can view the private member variable mQuery, which shows you the exact SQL query executed on that cursor - it's handy and can be used on demand without mucking with any code.
Since the query methods are of cursor type, I am not sure whether It will be printed or not.
If you want to debug any query, you can use EXPLAIN QUERY PLAN keyword along with the query or use SQLiteQueryBuilder() or simply run the SQL query by using rawQuery() method.
You can take references from:
http://developer.android.com/reference/android/database/sqlite/SQLiteQueryBuilder.html
http://www.sqlite.org/eqp.html
Hi I cant get unique rows tried this from the documentation:
public Cursor getcepaUnico(){
return database.query(true, "vino", new String[] {"_id", "cepa"}, null, null, null, null, "cepa", null);}
but shows duplicated rows even if the DISTINCT boolean is changed.
Also tried this:
public Cursor getCepaUnico() {
return database.rawQuery("select DISTINCT cepa from vinos", null);}
And the app crash after calling the method.
Setting distinct to true should have returned distinct results. Is it possible that your code which loops through the cursor is incorrect? You might want to post that also for review.
Regarding your rawQuery, you are using a different table name which is probably what is causing the crash. It should be "select DISTINCT cepa from vino" (not vinos) to match your query statement.
Not sure if this will solve your problem, but sometimes I just pull the db from the emulator (in the DDMS view in Eclipse) and run the query directly using an sqlite editor when my raw queries don't work; if the query shows what you want in the editor then use the query in the rawQuery method.
Firefox has a good sqlite editor.
I have a listview populated from an SQLite database. I have several items that I successfully populate into the listview, however I'm having trouble with one last thing.
I'm trying to queue the sum total of the column KEY_CONTENT6 which is a string type, however it only contains numbers. I'd like to keep it as a string, so to add it up I'm using Double.valueOf(). The problem is this code force closes on queue and I cant figure out whats wrong:
public Cursor queueAll(){
String[] columns =
new String[]{KEY_ID, "sum("+ Double.valueOf(KEY_CONTENT6) +")",
KEY_CONTENT9, KEY_CONTENT10 };
Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,
null , null, KEY_CONTENT10, null, KEY_CONTENT9+ " DESC");
return cursor;
}
simply use SUM, no need to use anything else..
String[] columns =
new String[]{KEY_ID, "sum(KEY_CONTENT6)",
KEY_CONTENT9, KEY_CONTENT10 };
It is valid for SQLite. Because, no matter what you set data type in SQLite, it stores values as string. So, type conversion is somewhat built-in in SQLite.
You can't use java in a SQL statement, either stick to strait sql or iterate over the cursor and use java to do your calculation.
You can find everything there is to know about sqlite here http://www.sqlite.org/docs.html
SQLite is basically typeless, so you might be able to use SUM on your column even though it is a string. However, if it's meant to be a numeric column, why not give it a number type??
I'm trying to do a relatively simple bitwise query operation with SQLite on Android. When I use bind variables, I get no data returned when I believe should get some rows back. If I hardcode the bind variable's value directly into the SQL, it works just fine. I'm thinking I have some silly syntax issue somewhere, but I just can't see it.
So this code works just fine:
String selection = new String(FLAGS + " & 2 = 2");
cursor = db.query(TABLE_NAME, ALL_COLUMNS, selection,
null, null, null, null, null );
This code however (using bind variables), returns no rows:
String selection = new String(FLAGS + " & ? = ?");
String[] selectionArgs = new String[]{"2", "2"};
cursor = db.query(TABLE_NAME, ALL_COLUMNS, selection,
selectionArgs, null, null, null, null );
They both result into a syntactically identical query being built when I inspect the cursor's mQuery property through the debugger. The latter does have the mBindArgs property populated correctly as well. I'm at a loss as to how this could be failing. There are no exceptions thrown or anything, it just doesn't return any rows.
I can take the failing query, and manually swap the question marks for the two's and paste it into the ADB SQLite command line interface and it works just fine as well.
If I am right the second query produces following condition:
& '2' = '2'
instead of
& 2 = 2
Try replacing & with AND
Make sure you have no ? characters in FLAG constant.
Besides what is a point of this logical condition?
I was facing the same problem as yours. As radek-k said, the query compares string.
One solution that may be performed is to use the following:
String selection = new String(FLAGS + " & ? = (0|?)");