Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to modify an item's value in a SQLite?

Tags:

android

sqlite

Supposing I have this sqlite database structure:

 ID     PRODUCT_NAME     AVAILABILITY 

  1       foo            0
  2       bar            1
  3       baz            0
  4       faz            1

How cand I modify the value of the AVAILABILITY fom 1 -> 0 where PRODUCT_NAME = 'bar' ? Something like this, Pseudocod:

db.execSQL( "UPDATE TABLE" + Table_name + "MODIFY" + availability + "=" + 0 + "WHERE" +  product_name + "like ? " + 'bar');

I assume that I also have to drop and recreate table using onCreate() and onUpgrade() methods, right? Some code will be highly appreciated.

like image 814
AlexAndro Avatar asked Dec 27 '22 04:12

AlexAndro


2 Answers

Use this:

SQLiteDatabase db=dbHelper.getWritableDatabase();
String sql="update "+Table_name+" set availability='0' where product_name like 'bar'";
Object[] bindArgs={"bar"};
try{
            db.execSQL(sql, bindArgs);
return true;
}catch(SQLException ex){
Log.d(tag,"update data failure");
return false;
}
like image 185
ρяσѕρєя K Avatar answered Jan 08 '23 06:01

ρяσѕρєя K


You want update not alter. alter is for the database schema, update is for the data stored in it.

For example: update TABLE_NAME set AVAILABILITY = 0 where PRODUCT_NAME like 'bar';

Also, do not just stick strings together to build an sql query. Use a prepared statement or other statement building library to avoid SQL injection attacks and errors.

like image 35
Joe Avatar answered Jan 08 '23 04:01

Joe