This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Get generated id after insert
I want to get the last inserted row id in my android application using this code :
String query = "SELECT * from SQLITE_SEQUENCE";
int createdUserId = Integer.parseInt(dbHelper.executeSQLQuery(query).toString());
but the problem is that it's throws an exception that cannot convert dbHelper.executeSQLQuery(query).toString() to integer. I'm not really good at sqlite ,but i think that this should return the last row id which was inserted...which will definitely will be int (at least I think this way). So if this is not the right way, can someone please guide me how to get the last row id in android application.
Thanks!!!
Your SQL statrment will return all the row ids, not just the latest. Try something like this...
SELECT ROWID from SQL_LITE_SEQUENCE order by ROWID DESC limit 1
Also note that I believe selecting from SQL_LITE_SEQUENCE will get the latest ID from ANY table, you can also access the SQL_LITE_SEQUENCE by selecting ROWID on any table, and getting just the IDs for that table. IE
SELECT ROWID from MYTABLE order by ROWID DESC limit 1
And thanks to MisterSquonk for pointing out the next step in the comments, adding it here for ease of reference later...
The query statement will then return a Cursor object containing the results, so to access the integer value you would do something like this (I'll substitute more common methods for your helper method, just for others sake)
String query = "SELECT ROWID from MYTABLE order by ROWID DESC limit 1";
Cursor c = db.rawQuery(query);
if (c != null && c.moveToFirst()) {
lastId = c.getLong(0); //The 0 is the column index, we only have 1 column, so the index is 0
}
(Note that although the SQL Lite docs call ROWID and Integer, it is a 64 bit integer, so in Java it should be retrieved as a long.)
Care to use "selectlast_insert_rowid()"? :)
Related
I have a sqlite db with 3 tables. TABLE1, TABLE2 and TABLE3.
I am using the following API to delete row(s) from the DB:
int rowsAffected = db.delete(tableName, "columnName=?", new String[] {String.valueOf(shoeId)});
Now, when I run this API for TABLE1 and TABLE2, the rows get deleted fine and I get the correct number in rowsAffected. But when i used this API for TABLE3, I always get rowsAffected as 0 and no entries are deleted.
int rowsAffected = db.delete(tableName, "columnName=?", new String[] {String.valueOf(shoeId)});
All 3 tables have the shoeId column.
Could someone please help?
Thanks.
The second parameter is the where clause, so you query should look like this :
int rowsAffected = db.delete(tableName, "nameOfColumn=?", new String[] {String.valueOf(shoeId)});
This means : "DELETE FROM tableName WHERE nameOfColumn = String.valueOf(shoeId)"
Don't remove the =?, it is used for prepared statements
The above query was not working due to the following reasons:
Lets say the columnName here is busTicketId and its data type is Int.
When the DB was created, the busTicketId was erroneously created as default String type due to an error in the Create table query.
As a result when the time came to delete busTicketId, it was trying to search for busTicketId, which was of Int type and since it could not find any, the rows affected count always turned out to be 0.
Once the data type issue for this column was fixed while creating the table, this issue also got fixed.
I have a column in my SQLite table named 'img_name'. An example of data in that column: '/storage/extSdCard/img1.jpg /storage/extSdCard/img2.jpg /storage/extSdCard/pic3.jpg'. Lets say I wanted to delete an image. I would delete the corresponding word(path). Only problem is, I do not know how to delete a specific word(path) from that column.
Any help will be appreciated.
The way to "delete a specific word" is to update the existing value.
So you will need an UPDATE statement which selects the appropriate rows, and changes the value of the column. The new value will have to be "computed" from the old value, as you would do in a programming language, using string functions.
UPDATE column1
SET column1 = trim(replace(column1||' ','/storage/extSdCard/img2.jpg ',''))
WHERE column2 = 'example'
Note that this is an example only. The correct string manipulation required may be different. Your question does not specify your exact requirements.
Please consult the SQLite documentation and internet articles for details of string functions in SQLite.
Note that this would not be necessary if you didn't store more than one value in a column in each row.
You should get id of your string that you need to remove, and then pass it in to this:
public void deleteById(int id)
{
SQLiteDatabase db=getWritableDatabase();
String[] position =new String[]{id+""};
db.delete("img_name", "id=?", position );
}
Note: "id=?". Replace "id" in this statement by your id column
I am new to Android, and having some basic problems. One of them is the use of queries.
I store a boolean value as either 1 or 0 in the table (INTEGER field). However, when I select either on 1 or 0 using the query below I get no results. What am I doing wrong?
Cursor cursor = _db.query(_objectName, _fields.keySet().toArray(new String[0]), "parentId=? AND published=?", new String[] {String.valueOf(menuItem), String.valueOf(1)}, null, null, "level");
There is nothing wrong with your query. The problem must be elsewhere. Check your code and table structure. Maybe you are not sending the right values for parentId and published columns or the data in the table is not in the format you expected.
Use raw query
"Select * from "+TABLE_NAME+" where published = '"+String.valueOf(1)+"'";
You can put your integer value insted of 1
Anyone know of a way to limit the number of rows deleted when using an sql DELETE statement?I just need to delete a row that holds a certain value one time instead of deleting every instance of the value. It's my understanding that the LIMIT clause cannot be added to DELETE statements in SQLITE. Now, I can't see a way to limit the number of rows deleted just using _id because I don't know what row _id will be deleted ahead of time; the rows are being deleted based on a value held in a variable and they could be anywhere in the DB. I hope this makes sense. Here's the delete statement:
String sql = "DELETE FROM strategyTotal WHERE strategy_prices = (?)" ;
db.execSQL(sql, new Double[] {subtractedStrategyPrice });
Use a subquery:
String sql = "DELETE FROM strategyTotal WHERE _id IN (SELECT _id FROM strategyTotal WHERE strategy_prices = (?) LIMIT 1);" ;
db.execSQL(sql, new Double[] {subtractedStrategyPrice });
delete from tablename where rowid in (
select rowid from tablename condition LIMIT 1)
try above work around or you may need to enable SQLITE ENABLE UPDATE DELETE LIMIT
my query is just an example. replace it with your own query.
In my android application, I have a SQLite database containing a table with an id column with AUTOINCREMENT. I'm using an INSERT statement to add a new row but I need to immediately access this row so I can refer to it by the ID. So does anyone know of a way to get the ID of this newly added row?
Thanks!
SQLiteDatabase.insert returns the id of the newly created row.
So, you would get the row like so:
long row = mDatabase.insert(MY_TABLE, "id", values);
(above of course is just an example)
See here: SQliteDatabase.insert
Returns
the row ID of the newly inserted row, or -1 if an error occurred
I think you can use last_insert_rowid() function
From documentation
The last_insert_rowid() function returns the ROWID of the last row insert from the database connection which invoked the function. The last_insert_rowid() SQL function is a wrapper around the sqlite3_last_insert_rowid() C/C++ interface function.
Try this out:
select id from myTable where id = (select max(id) from myTable);
When you insert a row, the long value which is return is the id of inserted row : see
public long insert (String table, String nullColumnHack, ContentValues values)
Copy past link :
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#insert(java.lang.String, java.lang.String, android.content.ContentValues)