Android. sqlite update last inserte row - android

I want to update the last inserted row, but I get an error:
08-20 12:08:23.091: E/AndroidRuntime(13598): android.database.sqlite.SQLiteException: near "ORDER": syntax error
(code 1): , while compiling: UPDATE REVIEW SET json=? WHERE ORDER BY
date DESC LIMIT 1
My code:
public int updateDataJSON(Review review) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_JSON, review.getJson());
return db.update(TABLE_REVIEW, values, " ORDER BY date DESC LIMIT 1", null);
}

You have to read the last date in a separate step:
db.update(..., "date = (SELECT max(date) FROM ReviewTable)", ...);
(If there are multiple rows with the same date value, this will update all of them.)

ORDER BY and such are only valid in SELECT queries, not UPDATEs.
Consider the following:
Store the last inserted row id as returned by a call to insert():
long lastInsertRowId = db.insert(...);
Use the rowid in the update like
db.update(TABLE_REVIEW, values, "ROWID=?", new String[] { String.valueOf(lastInsertRowId)2 });

Related

How can use sqlite update via ContentValues when want to update depend on current value and how can retrieve the Result?

I've a situation in sqlite that make you an example: My table has two fields,"_id" and "_score" . I have a record with _id=1, _score=10. I want to update this row to 5 number more than the current value(10). in SQL i can do it simple like:
Update my_table set _score = _score + 5 where _id = 1
but in sqlite I have these that I don't know how can fix it to what I want :
ContentValues values = new ContentValues();
values.put("_score", my_value);
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
int id = db.update(MY_TABLE,values,"_id = ?",new String[]{String.valueOf(my_id)});
and the Other problem is the returned value. I think in above example I give
id = 1
for 1 row effected. but I want to know that: Is there any way to retrieve the value of updated column(in my example I want to give "15"). Some thing like in SQL server that we fetch from
"##ROWCOUNT" or "##fetch_status"
Hope to describe it well. thanks.
Android's update() function can set only fixed values.
To execute your SQL statement, you have to use execSQL():
db.execSQL("Update my_table set _score = _score + 5 where _id = 1");
In SQLite, the UPDATE statement does not return any data (except the count of affected rows). To get the old or new data, you have to execute a SELECT separately.
For your first problem about updating the score value try this:
ContentValues values = new ContentValues();
values.put("_score", my_value);
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
int id = db.update(my_table, values, _id + " = ?",
new String[] { String.valueOf(my_id) });
}

How do I delete the last row of a SQLite table in Android. I don't have an _id column

Okay, so I have a high score table. I have two columns, Player name and score..
Every time a new score is to be added to the table I delete the last row, put the new score and new player name in the last row and then sort the table according to the score.
I can't delete the row with minimum score because there might be multiple entries with the same score and I don't want to delete all of them.
You might want to rebuild your table and include an id column with integer primary key autoincrement. You can do quite a bit with that column in place (here's an SO question you can look into for that).
Anyway I don't know how your process goes and why you need to delete the last row but here's an example of using an ID column to get the last row ( which I assume would be the latest insert and is what usually happens if you declare an ID integer primary key autoincrement column):
public int LastInsert() {
SQLiteDatabase db = this.getReadableDatabase();
final String MY_QUERY = "SELECT MAX(" + colID + ") FROM " + myTable;
Cursor cur = db.rawQuery(MY_QUERY, null);
cur.moveToFirst();
int ID = cur.getInt(0);
cur.close();
return ID;
}
From here you can probably just get the result of LastInsert and use that to direct what your delete function should delete.
Imo you're better of maybe just updating the last row instead of deleting and reinserting in it's place though. Something like this :
public int UpdateAcc(Account acc) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(colName, acc.getName());
cv.put(colScore, acc.getScore());
return db.update(myTable, cv, colID + "=?", new String[]{params});
}
I don't remember rather android with sqlite supports multiple commands per statement, but if so this might work:
DELIMITER ;;
SET #LastId = (SELECT ROWID FROM yourTable ORDER BY ROWID DESC LIMIT 1);;
DELETE FROM yourTable WHERE ROWID=#LastId;;
Otherwise you can store this in a integer variable:
SELECT ROWID FROM yourtable ORDER BY ROWID DESC LIMIT 1;
Then use that variable to run the next line
DELETE FROM yourtable WHERE ROWID=#ThatIntegerHere;

Android unable to escaping single quote character while SQLite database update

Hi in my database i have a string like "computer's" , i am fetching it from database and displaying listview, when i click on the list item it should store to one of my database table. I am doing it as below but it is getting crashed
public void updateFav(String key, int value) {
SQLiteDatabase db = mDbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
C_FAV=C_FAV.replaceAll("'","''");
values.put(C_FAV, value);
db.update(tableName, values, C_KEY + "='" + key.trim() + "'", null);
db.close();
}
Below is my trace
12-12 17:55:49.291: E/AndroidRuntime(18184): android.database.sqlite.SQLiteException: near "s":
syntax error (code 1): , while compiling: UPDATE fav SET favorite=? WHERE key='computer's'
You're escaping the apostrophes in C_FAV which seems to be a column name but not in key.
Consider using ? placeholder and bind arguments instead, e.g.
db.update(tableName, values, C_KEY + "=?", new String[] { key.trim() });

how to update new row in android sqlite database

Can anybody guide me.
I have an android app. That takes daily user entered value. I want that till same date on same day a user can enter n re-enter values in database , open or close app what ever but value just get updated till same date say for today 22/10/2014.
Now I have once inserted date value in my sqlite database. but if i just update it by user entered value so only one row is created n get updated, even if the date get change the next day.
But if I insert the date again then next row is created that I want actually.
My problem is that : now how to update my sqlite database at most recent date.
My update of user value from a checkbox is going through this method.
public long send(boolean a) {
ContentValues cv = new ContentValues();
cv.put(SEND_Today, a);
return ourDatabase.update(MY_DAILYTABLE, cv, DATE + "=" + "date", null);
it update all the rows as every row contain date column.
I want somthing like this
ourDatabase.update(My_DAILYTABLE , cv , "(select MAX(date) from My_DAILYTABLE )" , null;
update dailydata set daily = 10 where date = (select max(date) from dailydata) // because I know sqlite run this query successfuly
But whatever query I write I get error.
Can anybody guide me a correct query to achieve this functionality. Just need to know the write update query in Android SQLite.
You have to give the entire WHERE clause, that is, also the date =:
ourDatabase.update(My_DAILYTABLE, cv, DATE+" = (select...)", null);
you can follow this:
db.update(DB_TABLE, contentValues, DB_TABLE_ROW_NAME + " = ? ", new String[] { WHERE_DB_TABLE_ROW_VALUE });
should:
ourDatabase.update(MY_DAILYTABLE, cv, DATE + " =? " , new String[] { yourMaxDate });
Or use rawQuery:
String sql = "update dailydata set daily = 10 where date = (select max(date) from dailydata)";
Cursor cursor = db.rawQuery(sql, null);
if (cursor2.moveToFirst()) {
// can get column value as select query
}

Create a FIFO table with SQlite for Android application

I would like to create a FIFO table in order to save only the most 50 recent infomations by deleting the oldest elements when a new infomation arrives. I can do it by manipulating ID in the table but I don't think it is the best solution. Any idea of doing it well?
Instead of checking for date time, sorting your items, and whatnot, you can just assume that the first row in your table is the last to be inserted.
In your Content Provider's insert(Uri uri, ContentValues cv), before doing your db.insert call, you can first query the number of items on that table using getCount() and delete the first row if count>50. Then proceed with your insert call.
You dont need to play with IDs in order to create a FIFO logic. The best would be to add another column as DATETIME in your table which automatically inserts current time-stamp that will help you to select records in ascending order with respect to this column. Your new column should be something like:
DateAdded DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
Make sure when ever you insert new record, you must do a COUNT check of total records in this table and if necessary delete the oldest record with respect to DateAdded. Moreover, you can make use of LIMIT and/or MAX in your select-query when it comes to delete the oldest record.
Add a datetime type column to your table if it doesn't contain it yet and set it to 'now' on each insert. Then on each insert select all with limit set to 50 sorted by date. Choose the last item and run a delete query to delete everything older than this last item.
is it must to use sqlite? can you use file handling? you can use simple Queue object and save it to file.
Here is what I did for a list of transactions, and it works okay. When inserting a new entry I check if the count is above 50, if so, I just delete the very last entry:
// Adding new transaction
public void addTransaction(Transaction transaction) {
SQLiteDatabase db = this.getWritableDatabase();
if(getTransactionsCount() > 50){
List<Transaction> allTransactions = getAllTransactions();
Transaction oldestTransaction = allTransactions.get(allTransactions.size()-1);
deleteTransaction(oldestTransaction);
}
ContentValues values = new ContentValues();
values.put(KEY_TRANSACTION_UID, transaction.getUID());
values.put(KEY_TRANSACTION_AMOUNT, transaction.getAmount());
values.put(KEY_TRANSACTION_IS_ADD, transaction.getIsAdd());
// Inserting Row
db.insert(TABLE_TRANSACTIONS, null, values);
db.close(); // Closing database connection
}
And getAllTransactions() returns the list in descending order (based on the id primary key):
// Getting All Transactions
public List<Transaction> getAllTransactions() {
List<Transaction> transactionList = new ArrayList<Transaction>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_TRANSACTIONS + " ORDER BY " + KEY_TRANSACTION_ID + " DESC";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Transaction transaction = new Transaction();
transaction.setID(Integer.parseInt(cursor.getString(0)));
transaction.setUID(cursor.getString(1));
transaction.setAmount(cursor.getString(2));
transaction.setIsAdd(cursor.getString(3));
// Adding contact to list
transactionList.add(transaction);
} while (cursor.moveToNext());
}
// return contact list
return transactionList;
}

Categories

Resources