how to use whereClause, whereArgs when updating a table in sqlite? - android

In my android application i have tried to update a table using
sqliteDatabase.updateWithOnConflict(table, values, whereClause, whereClause, conflictAlgorithm)
method but i have no clear idea about whereClause and whereClause variables.following code will not give any exception or error but the table will not be updated.
AndroidOpenDbHelper androidOpenDbHelper = new AndroidOpenDbHelper(CreateListsActivity.this);
SQLiteDatabase sqliteDatabase = androidOpenDbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(AndroidOpenDbHelper.LIST_NAME, editedKeyword);
sqliteDatabase.updateWithOnConflict(AndroidOpenDbHelper.TABLE_NAME_LISTS, values, AndroidOpenDbHelper.LIST_NAME + "=" + id,null, SQLiteDatabase.CONFLICT_IGNORE);
sqliteDatabase.updateWithOnConflict(AndroidOpenDbHelper.TABLE_NAME_KEYWORDS, values, AndroidOpenDbHelper.LIST_NAME + "=" + id, null, SQLiteDatabase.CONFLICT_IGNORE);
sqliteDatabase.updateWithOnConflict(AndroidOpenDbHelper.TABLE_NAME_TWEET, values, AndroidOpenDbHelper.LIST_NAME + "=" + id, null, SQLiteDatabase.CONFLICT_IGNORE);
sqliteDatabase.close();
any suggestion??

Your conflict algorithm is IGNORE -
"When a constraint violation occurs, the one row that contains the constraint violation is not inserted or changed"
Does AndroidOpenDbHelper.LIST_NAME have a unique constraint on it which you may be violating? Try FAIL and check the return code:
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#CONFLICT_FAIL
Also, bind the parameters in the statement. Thats the correct way to use where clause and args -
sqliteDatabase.updateWithOnConflict(AndroidOpenDbHelper.TABLE_NAME_KEYWORDS, values, AndroidOpenDbHelper.LIST_NAME + "= ?" , new String[]{id}, SQLiteDatabase.CONFLICT_IGNORE);

you can write your own sql update statement like this:
String sql="update <tableName> set <columnName> = 'newValue' where <columnName>= 'oldValue' ";
sqliteDatabase.execSql(sql,null);

Related

Android - SQLite Update Statement

I am playing with an example of SQLite I found on the internet. I have an update statement like this:
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?" +
contact.getID(), null);
}
And an update statement like this:
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[]{String.valueOf(contact.getID())});
}
Can someone tell me the difference?
Here is the method signature for an update operation on SQLite database.
int android.database.sqlite.SQLiteDatabase.update(
String table, ContentValues values, String whereClause, String[] whereArgs)
From developer.android.com
You may include ?s in the where clause, which will be replaced
by the values from whereArgs. The values will be bound as Strings.
Btw your first example wouldn't work cause you have included
"KEY_ID + " = ?" + contact.getID()" in whereClause param and kept the whereArgs null. The ?s would'nt be replaced by your arg contact.getId()
Change whereClause in 1st example to this: KEY_ID + " = " + contact.getID()
On your 1st example.The code can't update anything.
The update method whereCause params will be convert to some SQL on where case ,It will replace the ? placeholder with whereArgs.
Such as:
In your 1st example.If contact.getId() return 1,The final SQL is like:
update contact set KEY_NAME = 'your contact name ' where KEY_ID = ? 1
but 2st example final SQL is like:
update contact set KEY_NAME = 'your contact name ' where KEY_ID = 1
So,the first example is not work.

How to update an entry for which I have a cursor in android?

I have the following query which returns a single element (at most):
Cursor cursor = db.query(
DATABASE_TABLE_SERIES,
new String[]{KEY_PRICE},
KEY_BOOK + " = ?",
new String[]{String.valueOf(bookId)},
null,
null,
KEY_DATE+" ASC",
"1"
);
I might need to update this particular single entry in the database. Here is what I try:
ContentValues changedValues = new ContentValues();
changedValues.put(KEY_PRICE, changedPrice);
db.update(
DATABASE_TABLE_SERIES,
changedValues,
"KEY_BOOK = ? ORDERBY "+ KEYDATE +" ASC LIMIT 1",
new String[]{String.valueOf(bookId)}
);
which does not work (as I expected).
How can I update the exact entry that I query with the query result? I strongly would prefer some example code, as I probably will not understand an explanation in text-form (I am an android-beginner)!
Replace:
"KEY_BOOK = ? ORDERBY "+ KEYDATE +" ASC LIMIT 1",
with:
"KEY_BOOK = ?",
There is no ORDER BY clause or LIMIT clause on an UPDATE statement.
To update this single entry, one must create a unique identifier. A unique identifier is the id in each table. So one must first select this unique identifier, then the remainder follows easily. Here is the example code:
Cursor cursor = db.query(
DATABASE_TABLE_SERIES,
new String[]{'id'},
KEY_BOOK + " = ?",
new String[]{String.valueOf(bookId)},
null,
null,
KEY_DATE+" ASC",
"1"
);
cursor.moveToFirst();
ContentValues changedValues = new ContentValues();
changedValues.put(KEY_PRICE, changedPrice);
db.update(
DATABASE_TABLE_SERIES,
changedValues,
"id = ?",
new String[]{cursor.getString(0)}
);
Of course, one could modify the first request to query both, the price and the id in one go, if that is suitable.

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

sqlite update a tuple

I was trying to update a row in sqlite db, but it gives syntax error. I think I'm missing something but I can't see it. Maybe you can help me.
Update code:
public void updateEntry(String oldname,String name,String mail, String phone,String adres)
{
ContentValues args = new ContentValues();
args.put(COLUMN_NAME, name);
args.put(COLUMN_EMAIL, mail);
args.put(COLUMN_PHONE, phone);
args.put(COLUMN_ADDRESS, adres);
sqLiteDatabase.update(MYDATABASE_TABLE, args,COLUMN_NAME + "=" + oldname, null);
}
Calling update (By the way t,t2,t3,t4 are EditTexts)
mySQLiteAdapter.updateEntry(isim, t.getText().toString(), t2.getText().toString(), t3.getText().toString(), t4.getText().toString());
Errors
07-30 11:34:56.487: E/AndroidRuntime(1990): android.database.sqlite.SQLiteException: near "smith": syntax error: , while compiling: UPDATE MY_TABLE SET Name=?, Phone=?, Email=?, Address=? WHERE Name=john smith
First I thought, I didn't give any address or phone as string, but I printed them and I see the correct values. Any idea where my fault is?
It is because you have not escaped oldname string which contains john smith.
use sqLiteDatabase.update(MYDATABASE_TABLE, args,COLUMN_NAME + "='" + oldname + "'", null);
or use
String whereClause = COLUMN_NAME + "=?";
String[] whereArgs = new String[] {oldname};
sqLiteDatabase.update(MYDATABASE_TABLE, args, whereClause, whereArgs, null);

update sql database with ContentValues and the update-method

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.

Categories

Resources