How to update a specific row in SQLite in android - android

I have a database having two columns COLUMN_ACCOUNT and COLUMN_PASSWORD, where the table looks like
COLUMN_ACCOUNT COLUMN_PASSWORD
facebook a
gmail b
twitter c
Now I want the row with name COLUMN_ACCOUNT = facebook have the COLUMN_PASSWORD changed from a to x. The resulting table will look like :
COLUMN_ACCOUNT COLUMN_PASSWORD
facebook x
gmail b
twitter c
I have tried using this function :
public int modifyCredentials(String account,String newPass){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put(COLUMN_PASSWORD,newPass);
String whereClause=COLUMN_ACCOUNT + " =?";
String[] whereArgs=new String[]{account};
int update=db.update(TABLE_NAME,contentValues,whereClause,whereArgs);
return update;
}
where the parameters account has the value facebook and pass has the value x, but it did not work. There is no problem with the parameters, I have double checked it and I think the problem lies in the sql query. Can you please help me out with the required sql query. Thank you :)

Read this page carefully: https://developer.android.com/training/basics/data-storage/databases.html.
It provides you everything you need.
Also you should not use db.execSQL(...);. Android provides you more convenient methods to insert, query, update and delete rows.

Add spacing in all the string literals you have as they might be the ones causing the issues you are experiencing.
Especially between the TABLE_NAME and " SET " so they can be explicitly different words

Try using void
public void modifyCredentials(String account, String newPass)
{
SQLiteDatabase db=this.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put(COLUMN_PASSWORD,newPass);
String whereClause=COLUMN_ACCOUNT + " =?";
String[] whereArgs=new String[]{account};
db.update(TABLE_NAME,contentValues,whereClause,whereArgs);
db.close();
}

Related

How to delete the rows from a table where a column contains a specific String?

As my title question, I want to delete some rows of table on SQLite where contains specific string.
Here are my methods I tried but there are no any row is deleted. I checked table of SQLite database by get it out and put in to DB Browser for SQLite which is downloaded from https://sqlitebrowser.org/
public void delete1(String table,String COLUMN,String link) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM "+table+" WHERE "+COLUMN+" LIKE "+link+"%");
}
public void delete2(String table,String name){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(table, "PRODUCTNAME" + "LIKE ?", new String[]{name+"%"}) ;
}
Could you tell me how to do it or how have i to correct code ?
using db.delete(table, "PRODUCTNAME " + "LIKE ?", new String[]{name+"%"}) ; will only delete rows that start with the value in name.
Perhpas you want :-
db.delete(table, "PRODUCTNAME " + "LIKE ?", new String[]{"%"+name+"%"}) ;
Then it would delete rows that contain the value rather than start with the value.
With db.execSQL("DELETE FROM "+table+" WHERE "+COLUMN+" LIKE "+link+"%"); you need to enclose the string in single quotes and assuming that you want to delete a row that contains the value then use :-
db.execSQL("DELETE FROM "+table+" WHERE "+COLUMN+" LIKE '%"+link+"%'");
Using the delete convenience method (the first part) is the better option as it protects against SQL Injection, it properly encloses the value, builds the underlying SQL and also returns the number of affected (deleted) rows.
If you use the following, this will write dome debugging information that may assist in debugging :-
public void delete2(String table,String name){
SQLiteDatabase db = this.getWritableDatabase();
Log.d("DELETEINFO","Attempting to delete rows with \n\t->" + name);
int deletedCount = db.delete(table, "PRODUCTNAME " + "LIKE ?", new String[]{"%"+name+"%"}) >0) ;
Log.d("DELETEINFO","Deleted " + deletedCount + " rows.");
}

Contacts are saved multiple times in Database

Hi guys i have code to add data into Database and that code is called on oncreate. but every time fragment is created its saves data into database again and again. I dont want that. how can i prevent that here is my code to get data and save it to database.
public void getcontacts(){
Cursor phones;
phones = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext()){
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
DataBaseOperations hell = new DataBaseOperations(getActivity());
SQLiteDatabase db = hell.getWritableDatabase();
hell.SaveContacts(name, phoneNumber, db);
}
phones.close();
}
here is code for saving in database.
public void SaveContacts(String Name,String phone,SQLiteDatabase db ){
ContentValues sv = new ContentValues();
sv.put(mDatabase.Tableinfo.Contacts_name, Name);
sv.put(mDatabase.Tableinfo.Contacts_phone, phone);
db.insert(mDatabase.Tableinfo.contacts, null, sv);
}
EDIT- Here is what i have done so far but how do i set a constraint on which it will conflict.I have added an auto increment primary key as unique key but how will they conflict?? but still its saving values again in database.where do i set a primery key as constraint?????
public void SaveContacts(String Name,String phone,SQLiteDatabase db ){
ContentValues sv = new ContentValues();
sv.put(mDatabase.Tableinfo.Contacts_name, Name);
sv.put(mDatabase.Tableinfo.Contacts_phone, phone);
db.insertWithOnConflict(mDatabase.Tableinfo.contacts, null, sv, SQLiteDatabase.CONFLICT_REPLACE);
EDIT- 2 - how would i make unique columns in this kind of query???
private static final String Contacts_Table = "CREATE TABLE "+
mDatabase.Tableinfo.contacts +"("
+mDatabase.Tableinfo.Contacts_name+" TEXT,"
+mDatabase.Tableinfo.Contacts_phone+" TEXT NOT NULL UNIQUE,"
+mDatabase.Tableinfo.isChattris+" TEXT,"
+mDatabase.Tableinfo.status_contact+" TEXT,"
+mDatabase.Tableinfo.Contact_pic+" BLOB"+")";
just Added NOT NULL UNIQUE.
This is the constraint.
Keep the status of the contacts saving in unrelated storage, e.g SharedPreferences. You don't want to rely on any lifecycle triggers, not even Application.onCreate, since that will happen again and again when the app is launched.
Try to update existing entries instead of adding new ones. Decide what the database key should be, and then you can use insertWithOnConflict with the CONFLICT_REPLACE flag to insert if not already in the table or update if it is.
EDIT: to define the constraints so the conflict behavior will trigger, change your CREATE TABLE statement. e.g this will cause duplicate (name,phone) pairs to trigger it. You may want to use some kind of contact ID instead though.
CREATE TABLE mytable (
name TEXT,
phone TEXT,
UNIQUE(name, phone)
)

Android / SQLite - backticks, single quotes or double quotes?

Suppose I had a method like this...
long getNumItemsFromDb() {
SQLiteDatabase db = dbhelper.getReadableDatabase();
try {
String query = "SELECT " + COL_NAME +
" FROM " + TABLE_NAME +
" WHERE " + COL_NAME + " = ?";
String[] args = new String[] {"whatever"};
return DatabaseUtils.longForQuery(db, query, args);
} finally {
db.close();
}
}
...but it's possible that, for example, String COL_NAME = "select"; and String TABLE_NAME = "from"; - which is going to break the query. So, I'd obviously need to surround those values in my query String with either backticks, single quotes or double quotes - but which of these is the best practice for Android / SQLite?
NB - I have simplified my query String above to make this question simpler and more to the point. So, in reality, I do need to create the SQL manually like this rather than using one of the helper methods in Android.
NB2 - I have seen similar questions here and here but the questions/answers do not address SQLite and Android.
I'd say go with the standard.
The ANSI standard is double quotes for quoting fields/identifiers, and that works well on SQLite.
Note that some other RDBMS's may need some help to follow the standard, but following it will allow your SQL to run unchanged on as many RDBMS's/platforms as possible.
If you were to use androids class SQLitedatabase you could just simply use the query method and not worry if your selection string contains any of the identifiers.
Though when using FTS tables with MATCH identifier I noticed that you must surround the searchable string with percent signs like this: "%"+str+"%", otherwise it only matches up until a space.

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

sqlite db update

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

Categories

Resources