Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqlite db update

Tags:

android

sqlite

Is there an easy way to update a table in sqlite in android? (like a single line in built method) ? I have a table with few columns and primary is one column. I want to search by the primary key and then update a row in the table.

like image 402
harsh Avatar asked Nov 29 '22 17:11

harsh


2 Answers

Read the documentation for SQLiteDatabase.update

You should end up with something like this:

affected = db.update(TABLE_NAME, values, where, whereArgs);

UDPATE

Avoid raw queries using error-prone syntax at all costs. I see a lot of answers here that use a lot of '"' + SOMETHING + "'" ... this is extremely bad practice and you will spend all your time looking for errors on places that are hard to find or simply a complete waste of time.

If you must use raw queries, try forming them with String.format to avoid perilous debug sessions and migraines.

like image 41
Moog Avatar answered Dec 06 '22 09:12

Moog


To use with predefined update method from android, use it as below:

ContentValues args = new ContentValues();
args.put("col_name", "new value");

db.update("table_name", args, String.format("%s = ?", "primary_column"),
           new String[]{"primary_id"});

Or to run as a single line, go with this (not recommended):

db.execSQL("UPDATE table_name SET col_name='new_value' WHERE
           primary_column='primary_id'");
like image 132
waqaslam Avatar answered Dec 06 '22 09:12

waqaslam