sqlite update a tuple - android

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

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.

Issue deleting row from database

So this seems pretty simple but I haven't been able to figure out what I'm doing wrong here. I have my database delete command:
public boolean deleteContact(String rowId) {
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
I also should mention that I am displaying the database in a listview. So when the user clicks on an item they are presented with a "OK" and a "Delete" option.
When they hit delete this is the command I'm using:
db.open();
db.deleteContact("Apple Recipe");
db.close();
dialog.dismiss();
I keep getting a force close issue that says:
android.database.sqlite.SQLiteException: ner "Recipe":syntax error
(code 1): , while compiling: DELETE FROM list WHERE item=Apple Recipe
I'm probably doing something stupid so maybe fresh eyes will help.
Add ' in your delete statement, like this :
return db.delete(DATABASE_TABLE, KEY_ROWID + "='" + rowId + "'", null) > 0;
Or, as mentionned by other posters, you can use separate parameters :
String whereString = KEY_ROWID + "= ?";
String[] whereArgs = new String[] { rowId };
db.delete(DATABASE_TABLE, whereString, whereArgs);
the delete method for a contentResolver takes, a Uri, a "where" string, and an args string.
and row id is most likely an int
So it should be something like this
db.delete(DATABASE_TABLE,"rowId = ? ", row_id_number);
or if you are looking to match some field such as "recipe" which is a string then.
assuming the field name is recipe:
db.delete(DATABASE_TABLE, "recipe = ?", "Apple Recipe");
To be honest you should be using:
return db.delete(DATABASE_TABLE, KEY_ROWID + "=?", new String[]{rowId}) > 0;
Its more of a safety thing to do with escaping the values to make sure no SQL is in the string that could execute

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;

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

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

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