Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

update sql database with ContentValues and the update-method

Tags:

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.

like image 613
spierala Avatar asked Sep 21 '10 13:09

spierala


People also ask

How to update Data in SQLite database in Android Studio?

In the above code, we have taken name and salary as Edit text, when user click on save button it will store the data into sqlite data base. Click on refresh button after insert values to update listview from cursor. If User click on update button it will update the data using salary.

How do I edit data in SQLite database?

Introduction to SQLite UPDATE statement First, specify the table where you want to update after the UPDATE clause. Second, set new value for each column of the table in the SET clause. Third, specify rows to update using a condition in the WHERE clause. The WHERE clause is optional.


2 Answers

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].

like image 96
TheContstruct Avatar answered Sep 17 '22 15:09

TheContstruct


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)

like image 43
Adam Javin Avatar answered Sep 20 '22 15:09

Adam Javin