Replace function in SQLITE - android

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.

Related

Not updating value in database instead Inserting new entry

I am using below code to update database and putting where clause for date
ContentValues values = new ContentValues();
values.put(DBTransactions.USER_ID_KEY, userId);
values.put(DBTransactions.DATE_KEY, date);
values.put(DBTransactions.DAY_KEY, day);
values.put(DBTransactions.GOAL_KEY, dailyGoal);
values.put(DBTransactions.VOLUME_KEY, dailyVolume);
values.put(DBTransactions.IS_GOAL_MET_KEY, goalMet);
db.getWritableDatabase().update(DBTransactions.TRANSACTION_TABLE_NAME, values, DBTransactions.DATE_KEY + " = ?", new String[]{date});
closeDB();
am I wrong somewhere in putting where clause? Its not updating database, Its creating new entry in database.
Its not updating database.
Thanks in Advance
I am using this code for update me Database and it's work fine , not a issue with me .
public void updateItemToCartTable(String itemId, String subitemid, String cost, int quantity) {
sdb = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ITEM_COST, cost);
values.put(ITEM_QUANTITY, quantity);
Log.d("DB", "Count : " + quantity);
this.sdb.update(TABLE_NAME, values, ITEM_ID + " ='" + itemId + "' AND " + SUB_ITEM_ID + " ='" + subitemid + "'", null);
sdb.close();
}
Use This Code For Updating your Database
Use below code to update your table:
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DBTransactions.USER_ID_KEY, userId);
values.put(DBTransactions.DATE_KEY, date);
values.put(DBTransactions.DAY_KEY, day);
values.put(DBTransactions.GOAL_KEY, dailyGoal);
values.put(DBTransactions.VOLUME_KEY, dailyVolume);
values.put(DBTransactions.IS_GOAL_MET_KEY, goalMet);
db.update(DBTransactions.TRANSACTION_TABLE_NAME, values, DBTransactions.DATE_KEY + " = ? ", new String[]{String.valueOf(date)});
closeDB();
What is data type of DBTransactions.DATE_KEY column in DBTransactions.TRANSACTION_TABLE_NAME table?
Insert data in local database and check the format in which date is inserting in DBTransactions.TRANSACTION_TABLE_NAME table.
While updating record based on DBTransactions.DATE_KEY condition, check DBTransactions.DATE_KEY matches value stored in DBTransactions.TRANSACTION_TABLE_NAME DBTransactions.DATE_KEY column.
Everything else in your code seems to be fine.

Android db.update where string

I'm using the method db.update to update the data according to the id.
now I would like at the same time change the same data that is present in another table. but the second part of the code does not work .... you have any ideas?
cv.put(CategorieTable.NOME_CATEGORIA, Ecatgoria.getText().toString());
String idc = id.getText().toString();
SQLiteDatabase db = mHelper.getWritableDatabase();
db.update(CategorieTable.TABLE_NAME, cv, idc + "=" + CategorieTable._ID, null);
//THE SECOND PART
cv.put(GiornateTable.CATEGORIA, Ecatgoria.getText().toString());
String nCategoria = Ecatgoria.getText().toString();
db.update(GiornateTable.TABLE_NAME, cv, nCategoria + "=" + GiornateTable.CATEGORIA, null);
You are using the same ContentValues instance (cv) for both operations. At second part you need to call cv.clear(), before put the new values.
cv.put(CategorieTable.NOME_CATEGORIA, Ecatgoria.getText().toString());
String idc = id.getText().toString();
SQLiteDatabase db = mHelper.getWritableDatabase();
db.update(CategorieTable.TABLE_NAME, cv, idc + "=" + CategorieTable._ID, null);
//THE SECOND PART
cv.clear(); // Clean the Content Values.
cv.put(GiornateTable.CATEGORIA, Ecatgoria.getText().toString());
String nCategoria = Ecatgoria.getText().toString();
db.update(GiornateTable.TABLE_NAME, cv, nCategoria + "=" + GiornateTable.CATEGORIA, null);

Update doesn't work sqlite android

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.

sqlite db update

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;
}

Android SQL Update statement

Can anyone tell me where I am going wrong with this SQL Update statement please?
SQLiteDatabase hashDB = openOrCreateDatabase(HASH_DB, MODE_PRIVATE, null);
hashDB.execSQL("CREATE TABLE IF NOT EXISTS " + HASH_TABLE1 + " (FileName VARCHAR, Hash VARCHAR);");
ContentValues updateFilesTable = new ContentValues();
updateFilesTable.put("Hash", hash);
hashDB.update(HASH_TABLE1, updateFilesTable, "FileName" + "=" + file, null);
file and hash are both Strings and I know they have the correct data in them, the records I am trying to update definitely exist in the database. HASH_TABLE1 also points to the correct table.
Many Thanks
Matt
You aren't quoting the file string. You want this line to read:
hashDB.update(HASH_TABLE1, updateFilesTable, "FileName = ?", new String[] { file });

Categories

Resources