Tuhin Subhra
Tuhin Subhra

Reputation: 356

SQLite Update Statement Is Not Working

I have an update statement that I'm trying to execute:

String update_stock = "UPDATE " + table_name_ + " SET " + current_stock + " = " + current_stock + " - " + sub_stock + " where item_name = '" + item_name + "'";
    getWritableDatabase().rawQuery(update_stock, null);

I've checked the query in log Log.d("updatesss", update_stock); which gave me:

UPDATE APPLE_CHILLAM SET current_stock = current_stock - 1 where item_name = 'Double Apple'

The value is not getting updated. What am I missing? The datatype of the current_stock column is in int.

Upvotes: 1

Views: 1907

Answers (2)

godot
godot

Reputation: 3545

Use execSQL instead of rawQuery:

execSQL("UPDATE " + table_name_ + " SET " + current_stock + " = " + current_stock - sub_stock + " where item_name = '" + item_name + "'");

Difference between execSql and rawQuery:

execSql

Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns data.

It has no means to return any data (such as the number of affected rows). Instead, you're encouraged to use insert(String, String, ContentValues), update(String, ContentValues, String, String[]), et al, when possible.

rawQuery

Runs the provided SQL and returns a Cursor over the result set.

Upvotes: 1

3iL
3iL

Reputation: 2176

Try something like this:

SQLiteOpenHelper dbHelper = new DBHelper(this);
SQLiteDatabase database = dbHelper.getWritableDatabase();

database.execSQL("UPDATE " + table_name_ + " SET " + current_stock + " = " + current_stock + " - " + sub_stock + " where item_name = '" + item_name + "'");

Upvotes: 1

Related Questions