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";
Related
I want to fetch phone number linked to particular email in the database. I am not able to find the query for it or how
public String getContactNumber(String email){
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT " + COLUMN_USER_MOBILE_NUMBER + " FROM " + TABLE_USER + " WHERE " + email + " = " + COLUMN_USER_EMAIL;
Cursor cursor = db.rawQuery(query,null);
//What to put here to extract the data.
String contact = cursor.getString(get);
cursor.close();
return contact;
}
to extract the data. Completely a beginner
Try this ..
public List<String> getMyItemsD(String emailData) {
List<String> stringList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT COLUMN_USER_MOBILE_NUMBER FROM " + USER_TABLE_NAME + " WHERE email= " + emailData;
Cursor c = db.rawQuery(selectQuery, null);
if (c != null) {
c.moveToFirst();
while (c.isAfterLast() == false) {
String name = (c.getString(c.getColumnIndex("Item_Name")));
stringList.add(name);
c.moveToNext();
}
}
return stringList;
}
public String getContactNumber(String email){
String contact = "";
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT " + COLUMN_USER_MOBILE_NUMBER + " FROM " + TABLE_USER + " WHERE " + email + " = " + COLUMN_USER_EMAIL;
Cursor cursor = db.rawQuery(query,null);
if(cursor.getCount()>0) {
cursor.moveToNext();
contact = cursor.getString(cursor.getColumnIndex(COLUMN_USER_MOBILE_NUMBER));
}
//What to put here to extract the data.
cursor.close();
return contact;
}
From this method you get phone number value of that email which you pass any other method easily.
I'd suggest the following :-
public String getContactNumber(String email){
String contact = "NO CONTACT FOUND"; //<<<<<<<<<< Default in case no row is found.
SQLiteDatabase db = this.getWritableDatabase(); //<<<<<<<<<< Generally getReadable gets a writable database
String[] columns_to_get = new String[]{COLUMN_USER_MOBILE_NUMBER};
String whereclause = COLUMN_USER_EMAIL + "=?";
String[] whereargs = new String[]{email};
Cursor cursor = db.query(TABLE_USER,columns_to_get,whereclause,whereargs,null,null,null);
//What to put here to extract the data.
if (cursor.moveToFirst()) {
contact = csr.getString(csr.getColumnIndex(COLUMN_USER_MOBILE_NUMBER));
}
cursor.close();
return contact;
}
The above does assumes that there will only be 1 row per email (which is most likely).
Explanations
A default value is set so that you can easily tell if an invalid/non-existent email is passed (you'd check the return value if need be (might be easier to simply have "" and check the length as a check)).
getReadableDatabase has been replaced with getWritableDatabase as unless there are issues with the database a writable database will be returned, as per :-
Create and/or open a database. This will be the same object returned
by getWritableDatabase() unless some problem, such as a full disk,
requires the database to be opened read-only. In that case, a
read-only database object will be returned. If the problem is fixed, a
future call to getWritableDatabase() may succeed, in which case the
read-only database object will be closed and the read/write object
will be returned in the future.
getReadableDatabase
Note no real problem either way;
The recommended query method has been used instead of the rawQuery method. This has distinct advantages, it builds the underlying SQL and also offers protection against SQL injection (just in case the email passed is input by a user).
this version of the method takes 7 parameters :-
The table name as a string
The columns to be extracted as an array of Strings (aka String array). null can be all columns.
The where clause less the WHERE keyword with ?'s to represent arguments (see next). null if no WHERE clause.
The arguments to be applied (replace ?'s 1 for 1) as a String array. null if none or no WHERE clause.
The GROUP BY clause, less the GROUP BY keywords. null if no GROUP BY clause.
The HAVING clause, less the HAVING keyword. null if no HAVING clause.
The ORDER BY clause, less the ORDER BY keywords. null if no ORDER BY clause.
SQLiteDatabase - query
- Note there are 4 query methods (see link for the subtle difference, I believe this is the most commonly used)
The data extraction is the new code. When a Cursor is returned it is at a position BEFORE THE FIRST ROW, so you need to move to a valid row. So the moveToFirst* method is suitable (note that if a move cannot be made by a move method that it will return false, hence how you can say if (cursor.moveToFirst())). The data is then extracted from the appropriate column use the **getString method, which takes an int as an argumnet for the column offset (0 in this case). However, using hard coded values can lead to issues so the getColumnIndex method is used to get the offset according to the column name (-1 is returned if the named column is not in the Cursor).
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();
}
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 });
Hi all I want to update a row on clicking on update button,but its doesn't work.
I have used following code.
public void btnUpdate(View v) {
handeler.updateData(updateName.getText().toString(), updatePhone .getText().toString(), updateEmail.getText().toString(),id);
}
public void updateData(String name, String phone, String email, String id) {
ContentValues values = new ContentValues();
values.put(COLUMN_FIRST, name);
values.put(COLUMN_SECOND, phone); values.put(COLUMN_THIRD, email); database.update(TABLE_NAME, values, id, null);
}
public void search() {
Cursor cursor = handeler.getData();
if (cursor.moveToFirst()) {
String phoneNo;
phoneNo = updateByPhone.getText().toString();
do {
String s1 = cursor.getString(2);
if (phoneNo.compareTo(s1) == 0) {
id = cursor.getString(0);
updateName.setText(cursor.getString(1));
updateEmail.setText(cursor.getString(3));
updatePhone.setText(cursor.getString(2));
}
} while (cursor.moveToNext());
}
}
So if any know please suggest me how to solve it.
Thanks
I see a couple possible issues:
1) You have an extra space updatePhone .getText().toString() should be updatePhone.getText().toString()
2) you are passing a variable id from btnUpdate to updateData but it is not clear where it is coming from (or even if it actually exists)
My bet is that #2 is your issue. You probably need to pass the id (I assume that's meant to be the RowId you want to modify in the db) in to the btnUpdate method:
public void btnUpdate(View v, long id)
There are other possibilities... you haven't shown your DB structure, so it could be that some constraint is causing the update to fail.
EDIT
The update method docs show this:
public int update (String table, ContentValues values, String whereClause, String[] whereArgs)
Note the part String whereClause. That's supposed to be a SQL WHERE statement (without the WHERE). You are only passing in the id, not a WHERE clause. Change your call to update to make that a WHERE clause and it should work. A couple of examples:
database.update(TABLE_NAME, values, "_id = " + id, null);
database.update(TABLE_NAME, values, "_id = '" + id + "'", null);
Both examples assume your row id column is labeled _id.
The first example is if id is an integer value. The issue there is that you are setting id as a string, so I'm unsure if this is the case or not. If it is supposed to be an int, you should get it using id = cursor.getInt(0); instead of id = cursor.getString(0);.
If it truly is a string and not an int, use the second version, which encloses id in single quotes to indicate it is a string.
Hope this helps!
Finally I got solution ,It was minor mistake,Using following code we can perform update operation
database.update(TABLE_NAME, values, BaseColumns._ID + "=" + id, null);
change the code
database.update(TABLE_NAME, values, "_id='?'", new String[]{id});
Edit
database.update(TABLE_NAME, values, "_id=?", new String[]{id});
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.