I have to execute the following query in Android SQLite
UPDATE player SET rank=rank+1 WHERE rank >= 3;
Here rank is the column name of INTEGER type.
I know about update method
update(tablename, values, whereClause, whereArgs);
I will pass player as first argument, rank >= 3 as 3rd argument and null as last argument but I am unable to find what to pass as 2nd argument. According to the docs it should be an object of ContentValues.
so I created its object as
ContentValues values = new ContentValues();
values.put("rank",?????);
I am confused about what to put the value for rank key which is a column in my table. Please suggest me what to pass as value to put() method of values
alternatively you can use exec , and execute your sql command
db.execSQL("UPDATE player SET rank=rank+1 WHERE rank >= 3");
to do it using the update method, you will need to get the current rank in a variable using Cursor, and then do the + thing manually "current+1"
I believe update method is not One-Size-Fit-All method. So I think you need to use rawQuery() to achieve this kind of sql execution. for example:
db.rawQuery("UPDATE player SET rank=rank+1 WHERE rank >= 3;", null);
or perhaps use execSQL as said by el7r
Related
This is a short snippet I found:
"Deleting data
Once data is no longer needed it can be removed from the database with
the delete() method. The delete() method expects 3 parameters, the
database name, a WHERE clause, and an argument array for the WHERE
clause. To delete all records from a table pass null for the WHERE
clause and WHERE clause argument array.
db.delete("tbl_states", "id=?", new String[] {Long.toString(countryId)});
Simply call the delete() method to remove records from the SQLite database. The delete method expects, the table name, and optionally a
where clause and where clause argument replacement arrays as
parameters. The where clause and argument replacement array work just
as with update where ? is replaced by the values in the array."
As usual I cannot find simple documentation as to:
How do I delete everything in the given table (I do not want to use .execSQL) via the .delete() method
What does it return? A cursor or interger? boolean?
Passing in null to the WHERE clause and argument array will delete everything (think if there is no WHERE clause all you are saying is delete from tbl_states).
delete returns the number of rows deleted as an integer.
This line, from your description, answers your first question:
...To delete all records from a table pass null for the WHERE clause
and WHERE clause argument array
db.delete("tbl_states", null, null);
The second answer: it returns the number of rows affected (or deleted, in integer) from the table. Say, you have 20 records in your "tbl_states" table, then, firing the above query will return 20 as integer.
int values = db.delete("tbl_states", null, null);
I'm writing an Android app that needs to write to the SQLite database. Currently it's using rawQueryWithString to build the update query, and I'm using ? placeholders in my query combined with the selectionArgs argument to pass in the actual values.
However, sometimes I actually want to update my column (of type Date) to NULL, but if I pass in null in my selectionArgs then I get this error:
IllegalArgumentException: the bind value at index 1 is null
I can't really see how I'm supposed to make it work when the value is actually null. I guess I could pass in an empty string, which in the case of a Date column like this might just work, but suppose it was a string column and I actually did want to mean NULL in contrast to the empty string (or are they considered equivalent in SQLite?)
Here's the code:
String timestampStr = null; // Obviously not really set like this
SQLiteDatabase d = getWritableDatabase();
DBCursor c = (DBCursor) d.rawQueryWithFactory(
new DBCursor.Factory(),
"Update subject set schedulingTimestamp = ? where identifier = ?",
new String[] { timestampStr, subjId.toString() },
null);
d.close();
The column was added with the following query, so I presume it's a nullable column since I didn't specify otherwise:
ALTER TABLE subject ADD schedulingTimestamp DATE;
Wildcards are not meant to be used for inserting/updating values in SQL, AFAIK. In Android, you can use ContentValues instead in conjunction with the update() method, instead of trying to shoehorn it in the raw query method.
I'm doing the following to insert information into the database:
ContentValues attachTags = new ContentValues();
attachTags.put("word_fk", "SELECT id FROM entry WHERE ent_seq = " + String.valueOf(line).substring(1));
attachTags.put("tag_id", gTagID);
// Insert the record
Uri insertUri = contentProvider.insert(Uri.parse(mContentProvider.CONTENT_URI + mContentProvider.PATH_SET_TAGS_ON_WORD), attachTags);
Unfortunately, word_fk is literally set to SELECT id FROM entry WHERE ent_seq = 1157170, like so:
id | word_fk | tag_id
52 SELECT id FROM entry WHERE ent_seq = 1157170 4
I intended for word_fk to be set to whatever is returned from the subquery, but it seems as though insert() doesn't execute subqueries when it inserts information into a database. I guess it's related to SQL input sanitization? In any case, how do I make this insert() query work?
I intended for word_fk to be set to whatever is returned from the
subquery, but it seems as though insert() doesn't execute subqueries
when it inserts information into a database. I guess it's related to
SQL input sanitization?
A ContentValues object is a simple map between some columns and the values, so you can't really use it to make sub queries, the data is used as it is.
However, it seems you control the ContentProvider so I don't see why you can't simply extract the sub-query from the ContentValues passed in the insert() method from the word_fk key and further use it directly to obtain what you want. Another approach would be to require that the Uri passed to the insert() method of the provider must contain an additional identifier(the ent_seq parameter in your example) if the word_fk is present in the ContentValues used.
I'm passing the below statement as a rawQuery in Android:
SELECT DISTINCT ltUsers._id,ltUsers.NAME,ltUsers.GLOBAL_ID, ltGroups.GROUP_NAME
FROM ltUsers
JOIN ltGroups ON (ltUsers.GROUP_ID = ltGroups.GLOBAL_ID)
WHERE ltgroups.GLOBAL_ID = ? " +
ORDER BY ltUsers.NAME ASC,ltgroups.GLOBAL_ID ASC;
With the rawQuery as follows:
Cursor c = db.rawQuery(sql,args)
It works just fine if I pass a value to the parameter, e.g.
String[] args = new String[]{"2"}
However, I also want to be able to show all rows, unlimited by the GLOBAL_ID in the WHERE clause. Testing on a dump of my SQLite database outside of Android - as well as in Android by just writing the parameter directly into the statement - shows the following clause to be a valid way to do this:
WHERE ltGroups.GLOBAL_ID = ltGroups.GLOBAL_ID
Yet when I pass the field reference ltGroups.GLOBAL_ID or [ltGroups].[GLOBAL_ID] as a parameter it fails to return any rows in the rawQuery. Any ideas on why this might be happening? Happy to produce any extra information.
Parameters always replace specific values, not anything else.
When you put the string "ltGroups.GLOBAL_ID" into the parameters array, it is interpreted as exactly that, a string.
(To show all records, just omit the WHERE clause.)
When I try to put some condition value into ContentValues variable, there is inserting as String.
contentValues = new ContentValues();
contentValues.put("DLM", "julianday('now', 'localtime')");
After executing
count = db.update(TABLE_NAME, contentValues, selection, selectionArgs);
the field is updated but the value is incorrect. I need to have the numeric date in the field, not string.
Another problem if I need to update existing field with the calculated value:
UPDATE tbl SET field=field*2
When I put the value like
contentValues.put("field", "field*2");
It has put the value as String. How I can get the value I really needed?
I think instead of update() method you should use execSQL method which allows you completely control the query syntax. Also instead of calculating fields in query you might consider creating triggers.
you need to enter date like:
Calendar cal=Calendar.getInstance();
ContentValues values = new ContentValues();
values.put("DLM", String.format("%1$te-%1$tB-%1$tY",cal));//this will insert date with format 2 July 2011
For updating values like fieldValue*2,
you need to fetch the older values from table and then you need to pass it like:
values.put("field_name",new_field_value);