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.
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'");
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.
You can use rawQuery like this:
cur = mDb.rawQuery("update " + TABLE_NAME
+ " set column1=mango where id='" + _id + "'",null);
where
cur is Cursor object
TABLE_NAME is NAME OF THE TABLE
_id is name of the column (only example)
Then you should already know what's your primary key.
dbHelper.getWritableDatabase();
ContentValues values = createContentValues(profileVo);
db.update(ProfileVO.TABLE_NAME, values, ProfileVO.COLUMN_ID + "=" + profile.getId(), null)
Here's a good tutorial for you http://www.vogella.com/articles/AndroidSQLite/article.html
The answer is:
http://www.sqlite.org/lang_update.html
and
SQLiteDatabase.rawQuery(...)
Try this:
public void updateFunction(int id) {
String updateStmnt = "UPDATE YOUR_TABLE SET YOUR_COLUMN = "
+ id;
database.execSQL(updateStmnt);
}
Hope it will help.
Using database.update make it simple like this:
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_NAME, name);
values.put(MySQLiteHelper.COLUMN_JOB, job);
values.put(MySQLiteHelper.COLUMN_DATE_START, date_start);
database.update(MySQLiteHelper.TABLE_EMPLOYEES, values, MySQLiteHelper.COLUMN_ID+"="+id, null);
I know this a bit old, but in case anyone needed another way:
public boolean updateNote(Note note) {
SQLiteDatabase db = notesDbHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(NotesDbContract.NoteEntry._ID, note.getId());
contentValues.put(NotesDbContract.NoteEntry.COLUMN_NAME_TITLE, note.getTitle());
contentValues.put(NotesDbContract.NoteEntry.COLUMN_NAME_DSECRIPTION, note.getDescription());
int result = db.update(NotesDbContract.NoteEntry.TABLE_NAME,
contentValues,
NotesDbContract.NoteEntry._ID + "=?", new String[]{String.valueOf(note.getId())}
);
db.close();
return result > 0;
}
Related
I was trying to duplicate this SQLite statement from the line of code below:
Cursor cursor = db.rawQuery("update tbl_details SET ticket = replace(ticket, " + tempID + ", " + ticket + ")", null);
to this one:
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("ticket", "replace(ticket, " + tempID + ", " + ticket + ")");
db.update("tbl_details", cv, null, null);
return true;
What I am trying to do is to get a New ID and replace all instances of the old temporary ID in the database. But the code above is changing all the records in ticket column.
Please help. Thank you!
You can use ContentValues to bind literal values only, not expressions like replace(...).
To run the raw UPDATE SQL, just use execSQL() instead of rawQuery(). rawQuery() alone won't actually run the code until the returned Cursor is moved.
I have the table(shown in fig). I want to update the time column. I have the medicine_id(second column) how to update the different times depend upon the same medicine_id(second column).
Also, I have four rows in my DB when I updated time it should be two row means, I want to remove the other two rows with the particular medicine_id..
I have the following code for update:
if(mon) {
for (int i = 0; i < dosage_per_day; i++) {
mMedicineDbHelper.updateMedicines(new
MedicineTime(row_id, time_InMillies[i]));
}
}
My DB code:
public void updateMedicines(MedicineTime medicineTime) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ID, medicineTime.getId());
values.put(MEDICINEID, medicineTime.getMedicine_id());
values.put(TIME, medicineTime.getTime_in_millis());
db.update(TABLENAME, values, MEDICINEID + " = ?",
new String[]{String.valueOf(medicineTime.getMedicine_id())});
db.close();
}
It shows exception..
anybody help to solve this...
For the original question asked you're executing the following code:
db.update(TABLENAME, values, MEDICINEID + " = ?",
new String[]{String.valueOf(medicineTime.getMedicine_id())});
For some reason on Android, converting numeric values to Strings and using them for selection args never works properly. See: Android Sqlite selection args[] with int values. The best way to do this is the following:
db.update(TABLENAME, values, MEDICINEID + " = " + medicineTime.getMedicine_id(), null);
Having problem updating a column in a table. I tried both of these solutions:
this.openDataBase();
String SQLStatement = "update " + TABLE_POSES;
SQLStatement += " set " + COLUMN_SKIP + "=" + SKIP + " Where ";
SQLStatement += COLUMN_ID + "=" + String.valueOf(skipPoseId);
myDataBase.rawQuery(SQLStatement, null);
this.close();
and this:
this.openDataBase();
ContentValues args = new ContentValues();
args.put(COLUMN_SKIP,SKIP);
myDataBase.update(TABLE_POSES, args, COLUMN_ID + "=" + String.valueOf(skipPoseId),null);
this.close();
Neither of these code snippets work and I am not getting any exceptions thrown. What am I doing wrong?
You should use the second method using update() and you should check the return value. If the value is zero, then the state of the database isn't what you expect and no rows were updated. If the row is not zero then the updating is succeeding.
If anything is wrong with your accessing the database an exception will be thrown before the update() call.
I would take advantage of the args parameter of update() like so:
myDataBase.update(TABLE_POSES, args, COLUMN_ID + " = ?", new String[]{ Long.toString(skipPoseId) });
Use update like this,
String query="UPDATE tablename SET columnname="+var+ "where columnid="+var2;
sqlitedb.execSQL(query);
Just write your update query in String query and execute.
if you use db.begintransaction() in your code you must call db.setTransactionSuccessful() before db.endtransaction() such as:
try {
SQLHelper dbHelper = new SQLHelper(this);
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.beginTransaction();
...................
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
catch (Exception ex){
}
I had the exactly same issue. After much thought and debugging I saw that the WHERE condition wasn't addressing any rows of the table.
The odd thing is that the myDatabase.update command giving 1 as the return and I was understanding it as 1 row affected by the update.
Sorry if this seems obvious. I'm trying to write a method to delete a row from a String showId. What would be the best way, and can Cursors only be used for Selects or also for Deletes and Updates?
These are the two methods I'm at so far:
public int deleteShowById1(String showId){
Cursor cursor = db.rawQuery("DELETE FROM tblShows WHERE showId = '" + showId+"'", null);
if (cursor.moveToFirst()) {
return 1;
} else
return -1;
}
public int deleteShowById2(String showId) {
String table_name = "tblShows";
String where = "showId='"+showId+"'";
return db.delete(table_name, where, null);
}
As we know from mysql query, it is same here in android.
String query = "DELETE FROM " +TABLE_NAME+ " WHERE " + COLUM_NAME+ " = " + "'"+VALUE +"'" ;
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(query);
db.close();
VALUE may or may not have single quotation depending on datatype.
I tend to use the second method (db.delete), as I think using rawQuery is frowned upon.
If you do a select, then loop through the cursor to do updates or deletes, that would make sense, but to pass a cursor to do the delete or update doesn't make sense to me, as the program won't know how to parse the cursor results to get the correct fields.
I would like to update my SQL lite database with the native update-method of the SQLiteDatabase class of android.
ContentValues dataToInsert = new ContentValues();
dataToInsert.put("name", "flo");
dataToInsert.put("location", "flotown");
String where = "id" + "=" + id;
try{
db.update(DATABASE_TABLE, dataToInsert, where, null);
}
catch (Exception e){
String error = e.getMessage().toString();
}
but I get following error:
android.database.sqlite.SQLiteException: near "15": syntax error: ,
while compiling: UPDATE mytable SET location=?, name=? WHERE
id=2010-09-21 15:05:36.995
I don´t know what should be the problem. Somehow the values do not arrive in the SQL statement. I did nearly the same with the insert method and that worked quite fine.
You're using the update function wrong. It should be like this:
String where = "id=?";
String[] whereArgs = new String[] {String.valueOf(id)};
db.update(DATABASE_TABLE, dataToInsert, where, whereArgs);
The Strings in the whereArgs array gets substituted in for each '?' in the where variable.
ie. if you had where = "name=? AND type=? then the first '?' would get replaced by whereArgs[0] and the second by whereArgs[1].
Actually, you just need to add apostrophes to your where clause. So it ought to be:
String where = "id='" + id + "'"
(note: however, this is not best practice, as it theoretically leaves open to injection attacks)
I have an other approach
public boolean updateEmployee(TalebeDataUser fav) {
SQLiteDatabase database = dbHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(DBHelper.COLUMN_ID, fav.getId());
contentValues.put(DBHelper.COLUM_AD, fav.getAd());
contentValues.put(DBHelper.COLUMN_NUMARA, fav.getNumara());
contentValues.put(DBHelper.COLUMN_YURD_ID, fav.getYurtID());
contentValues.put(DBHelper.COLUMN_EGITIM_ID, fav.getEgitimTur());
contentValues.put(DBHelper.COLUMN_TEL, fav.getTel());
contentValues.put(DBHelper.COLUMN_EMAIL, fav.getEmail());
contentValues.put(DBHelper.COLUMN_ADDRESS, fav.getAdres());
String whereClause = DBHelper.COLUM_AD + " = ? AND " + DBHelper.COLUMN_NUMARA + " = ? ";
final String whereArgs[] = {fav.getAd(), String.valueOf(fav.getNumara())};// old nameler taranıyor
int affectedRows = database.update(DBHelper.TABLE_NAME_OGR, contentValues, whereClause, whereArgs);
return affectedRows > 0;
}
Actually what exactly you written is correct. The syntax is correct.
But you have to check these.
String where = "id" + "=" + id;
In the above declaration "id" should be type number and id should be int.
And if id is a type of TEXT then follow #Adam javin answer.