update sql database with ContentValues and the update-method - android

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.

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 table in sqlite android

In my app i want to update my database table based on two column.Means update salary where firstname="ekant" and last name="kancha".So can any body plz tell me what will be the query i have to write.
public int updateStatus(int salary,String fname,String lName)
{
ContentValues cv=new ContentValues();
String where = fname+ "=" + "ekanta";
cv.put("salary",salary);
return sdb.update(DATABASE_TABLENAME, cv, where, null);
}
this code works only when i want to update based on first name..But i want to update based on firstname and lastname.
plz help me.thanx
Use placeholders. This makes it easier to read the SQL query and protects against SQL Injection (accidental or otherwise).
public int updateSalary (int salary, String fname, String lName)
{
ContentValues cv = new ContentValues();
cv.put("salary", salary);
/* use COLUMN NAMES here */
String where = "firstname = ? and lastname = ?";
/* bind VALUES here */
String[] whereArgs = new { fname, lname };
return sdb.update(DATABASE_TABLENAME, cv, where, whereArgs);
}
If you have constants (e.g. private final static COLUMN_FNAME = "firstname") for the COLUMN NAMES, then you can build where using these constants.
However, do not put VALUES in the where string. Instead, use ? and supply any VALUES via the whereArgs array as per the above example.
Also, it is possible for people (even within the same organization) to share the same first name and last name. Basing the database queries/updates around such a pairing will break in such cases so it may be prudent to work on designing the API to work with a better record identifier.
use this...
String where = fname+ "=" + "ekanta" + " and " + lname + "=" + "your lastname";

Get all unique values from SQLite column as string array

I try to get all unique values from database coulmn using SELECT DISTINCT sql command.
But i get exception when my activity is loading, i have this error code in logcat:
05-05 09:08:32.637: E/AndroidRuntime(1314): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.workoutlog/com.example.workoutlog.AddWorkOutPage}: android.database.sqlite.SQLiteException: near "SELECT": syntax error (code 1): , while compiling: SELECT * FROM exerciseTable WHERE SELECT DISTINCTexercise_typefromexerciseTable
I think that i have not wrote the command correctly, here is my code:
public String[] getAllExercies() {
String selecet = "SELECT DISTINCT" + COLUMN_EXERCISE + "from" + TABLE_NAME;
Cursor c = ourDatabase.query(TABLE_NAME, null, selecet, null, null, null, null);
int dayExercise = c.getColumnIndex(COLUMN_EXERCISE);
String[] list = new String[c.getCount()-1];
int j = 0;
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
list[j] = c.getString(dayExercise);
j++;
}
return list;
}
I think you should first checkout these answers here and here in order to see the working of .query() function.
Please note that while using ourDatabase.query() function, the parameters are as follows:
String Table Name: The name of the table to run the query against
String [ ] columns: The projection of the query, i.e., the columns to retrieve
String WHERE clause: where clause, if none then pass null
String [ ] selection args: The parameters of the WHERE clause
String Group by: A string specifying group by clause
String Having: A string specifying HAVING clause
String Order By by: A string Order By by clause
So your third variable should be a WHERE clause, something like:
String[] args = { "first string" };
Cursor c = ourDatabase.query("TABLE_NAME", null, "exercise_type=?", args, null, null, null);
Since you don't need a WHERE clause, for your purposes you might want to use rawQuery() method instead.
String selecet = "SELECT DISTINCT " + COLUMN_EXERCISE + " FROM " + TABLE_NAME;
ourDatabase.rawQuery(selecet, null);
Update
Try the answer from here. Do something like this:
Cursor c = ourDatabase.query(true, "exerciseTable", new String[] {"exercise_type"}, null, null, "exercise_type", null, null, null);
int dayExercise = c.getColumnIndex(COLUMN_EXERCISE);
//... continue with your further code
Hope this helps else please comment.
Issue:
you have not maintained the space between the words.
Explaination:
suppose, String COLUMN_EXERCISE = "exercise";
and String TABLE_NAME = "tbl_workout";
then
String selecet = "SELECT DISTINCT" + COLUMN_EXERCISE + "from" + TABLE_NAME;
simply means,SELECT DISTINCTexercisefromtbl_workout
Solution:
String selecet = "SELECT DISTINCT " + COLUMN_EXERCISE + " from " + TABLE_NAME;
Edit:
Kindly use following syntax to fire rawQuery
Cursor c = ourDatabase.rawQuery(selecet,null);
I hope it will be helpful !
You miss all the spaces in your query, you should replace with this:
String selecet = "SELECT DISTINCT " + COLUMN_EXERCISE + " FROM " + TABLE_NAME;

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 method doesn't update database with value

Here is my piece of code which runs without errors, but doesn't update database:
ContentValues cv_lio = new ContentValues();
cv_lio.put("u_lio",1);
String where = "u_name" + "=" + 5;
db.update(table_name, cv_lio,where,null);
Can anyone improve my update query to work well.
Proceed as follow :
ContentValues cv_lio = new ContentValues();
cv_lio.put("u_lio",1);
String where = "u_name" + " = ?";
String[] whereArgs = new String[] {String.valueOf(5)};
db.update(table_name, cv_lio, where, whereArgs);
please refer to documentation which is, I must confess, not so clear on that precise point...
The error was at where clause corrected code can be
ContentValues cv_lio = new ContentValues();
cv_lio.put("u_lio",1);
String where = "u_name='" + un + "'";
db.update(table_name, cv_lio,where,null);
Look for Quotes when you want to show field value like the one shown above..

Categories

Resources