0

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

1
  • 1
    Try this: String where = fname+ "=" + "ekanta" + " AND " + lname+"=" +"lastName"; Commented Oct 27, 2013 at 5:53

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

2

use this...

 String where = fname+ "=" + "ekanta" + " and " + lname + "=" + "your lastname";

3 Comments

Besides resulting in invalid SQL, this is too hard to read and too easy to break.
Actually I was just seeing his code and he said ( String where = fname+ "=" + "ekanta";) is working. So I just told about lastname. Obviously you answer is the best.
I'm surprised that "somefirstname=ekanta and.." is even valid.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.