Mehdi
Mehdi

Reputation: 540

Update multiple rows in Android sqlite

I have table contains columns id, name, profession, age, hobby, country, sex. Now I want to update the fields where sex is female and age is 30. All the fields are text (String). First, I am counting all the rows then running a loop to update the rows. Loop is running as per the total rows but rows are not updated... WHY? Where I have done the mistake? Here is my code:

METHODS FOR ANDROID SQLITE DATABASE QUERY:

public void updateUser(String newProfession, String newCountry, String sx, String ag) {
    SQLiteDatabase db = this.getWritableDatabase();
    String query = "UPDATE "+TABLE_USER+" SET "+KEY_PROFESSION+"='"+newProfession+"', "+KEY_COUNTRY+"='"+newCountry+"' WHERE "+KEY_SEX+"='"+sx+"' AND "+KEY_AGE+"='"+ag+"'";
    Cursor cursor = db.rawQuery(query, null);
    cursor.close();
    db.close();
}

public int countAll() {
    String countQuery = "SELECT  * FROM " + TABLE_USER;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    int cnt = cursor.getCount();
    cursor.close();
    db.close();
    return cnt;
}

CALLING THE METHODS

public void updateUsersClicked(View view) {
    int allData = db.countAll();
    for (int i = 0; i < allData; i++) {
        db.updateUser("SENIOR ENGINEER", "CANADA", "female", "30");
        System.out.println("T H I S    I S    T H E    R E S U L T: " + i);
    }
}

Upvotes: 2

Views: 6075

Answers (2)

laalto
laalto

Reputation: 152797

Use execSQL() and not rawQuery() for updates.

rawQuery() just compiles the SQL and requires one of the moveTo...() methods on the returned Cursor to execute it. execSQL() both compiles and runs the SQL.

Also consider using ? parameters with bind args in your SQL to avoid escaping special characters and being vulnerable to SQL injection.

Upvotes: 2

yossico
yossico

Reputation: 3521

You don't need to do the for loop a single QSL "Update" query is enough if you want to update All the female with age 30.

If you are new to SQL you can view a simple example here: Simple SQL Update example

If you want to do something else - please edit your question

Upvotes: 1

Related Questions