I get a string stored in the db to change it. I'm stuck in the method db.update because I have to change all the strings that match the value received. for example I have 15 records in field1 with the string "sun" and change it to "sun1" need to be changed all the correspondents.
I tried that but it does not work
cv.put(MyTable.FIELD1, Ec.getText().toString());
String cat_modificare = (i.getStringExtra("value"));
db.update(MyTable.TABLE_NAME, cv, cat_modificare + "=" + MyTable.FIELD1, null);
When you write something into the whereClause, it is interpreted as a column name unless you format it correctly.
String values should always be used as parameters:
db.update(MyTable.TABLE_NAME, cv,
MyTable.FIELD1 + " = ?",
new String[] { cat_modificare });
Related
I got stuck in a very strange issue. Where i am able to update the db Values when when trying to fetching the rows corresponding to that values i am not getting anything.
In this database, i inserted these rows, the date were 29, june for the last two rows, but when i updated these dates to 15, and tried to fetch the rows corresponding to that date
String where = COL_DATE + " = ?";
String[] args = {"15"};
Cursor cursor = db.query(TABLE_DAILY_EXPENSE, null, where, args, null, null, null);
Then Log.d(TAG, "Cursor count= " + cursor.getCount());gives 0`
Where as by fetching through month, it gives count = 2.
So i concluded, that somewhere after updating the fields, its not matching that updated field for fetching that corresponding row. But why this is happening?? No Idea.
`
The value in the database is a number.
The value you are searching for is a string, which is different.
The Android database API allows only strings as parameters in most places, so you have to insert the number directly into the SQL command:
String where = COL_DATE + " = " + 15;
String[] args = null;
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";
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;
}
Hi to All I am new to Android.
I am using SQLite DataBase in my Application
meanwhile I am Written Queries using +
Like delete from tablename where value = + value;
this is my query
String delete_query = "delete from " + tableName
+ " where title = '" + title + "'";
database.execSQL(delete_query);
I want to write this Query using placeholder ?.
so that i tried
database.delete(tableName, title + "?" , new String[] {title});
instead "?" i tried (?)/('?')/'?'
but it is giving me an error....
can any one tell me how to write appropriate query using ?.....
Thanks in Advance.
Mahaveer
Make sure you have put the equal sign:-
database.delete(tableName, title + "=?" , new String[] {title});
As far as possible, try to use the less raw queries you can. Two advantages:
Query parameters will be escaped by the system (protection against SQL injection)
The code will be more readable
See the delete function of SQLiteDatabase class
public int delete (String table, String whereClause, String[]
whereArgs)
Convenience method for deleting rows in the
database.
table the table to delete from
whereClause the optional WHERE clause
to apply when deleting. Passing null will delete all rows.
Returns the number of rows affected if a whereClause is passed in, 0
otherwise. To remove all rows and get a count pass "1" as the
whereClause.
In your case:
final String where = "title=?";
final String[] args = new String[] { title };
database.delete(tableName, where, args);
So I have data in my database & the value of category is set to "Breakfast"
When I execute the below Query with whereClause as
1:final String whereClause = RECIPE_ID + "=1";
It returns me the data for that RECIPE_ID
But when I execute the query with whereClause as
2:final String whereClause = RECIPE_CATEGORY + "='" + category.trim() + "'";
It doesn't return anything... So I guess my code is working fine as it returns result
RECIPE_ID but I donno why it doesn't return data for the 2nd whereClause
Hope this makes sense..
final String whereClause = RECIPE_CATEGORY + "='" + category.trim() + "'";
// ask the database object to create the cursor.
cursor = db.query(
RECIPE_TABLE,
new String[]{
RECIPE_ID,
RECIPE_CATEGORY,
RECIPE_THIS_TITLE,
RECIPE_THIS_SUBTITLE,
RECIPE_THIS_DESCRIPTION,
RECIPE_THIS_IMAGE,
RECIPE_THIS_CALORIES,
RECIPE_THIS_FAT,
RECIPE_THIS_SATURATED,
RECIPE_THIS_TRANS,
RECIPE_THIS_CARBS,
RECIPE_THIS_SODIUM,
RECIPE_THIS_SUGARS,
RECIPE_THIS_SERVINGS,
RECIPE_THIS_COSTPERSERVING,
RECIPE_THIS_INSTRUCTIONS,
RECIPE_THAT_TITLE,
RECIPE_THAT_CALORIES,
RECIPE_THAT_FAT,
RECIPE_THAT_SATURATED,
RECIPE_THAT_TRANS,
RECIPE_THAT_CARBS,
RECIPE_THAT_SODIUM,
RECIPE_THAT_SUGARS,
RECIPE_THAT_PRICE
},
whereClause, null, null, null, null
);
The above code will not return any results. Is anything wrong with it?
You really need to form a question here. Posting code does you no good. If your question is as you title implies, then yes you can do a search clause as a string. Just leave out the where. eg dataId = 5 where 'where' is implied.
Edit: to address the question at the bottom that I missed, multiple things could be wrong. One may be that you dont have any data in the database. Or the where clause is executed and none of your data fits the criteria. Check your database. We can't help with that.