Star_Man
Star_Man

Reputation: 1091

How do I get updated row count using sqlite in Android?

I am developing a app using sqlite database in android. Here is my table DDL code.

db.execSQL("CREATE TABLE 'ad_img' (" +
"'ad_img_uid'  INTEGER PRIMARY KEY AUTOINCREASE NOT NULL," +
"'ad_uid'  INTEGER," +
"'ad_img_url'  TEXT(255) NOT NULL," +
"'ad_img_local'  TEXT(255) NOT NULL" +
")");

And this is my update sql code.

public int updateLocalPathTOAdImg(int ad_uid, String ad_img_url, String ad_img_local) {
        int result = 0;

        try {
            String sql = "UPDATE 'ad_img' SET " +
                    "'ad_img_local' = '" + ad_img_local + "' " +
                    "WHERE 'ad_uid' = " + ad_uid + " AND 'ad_img_url' = '" + ad_img_url + "'";
            m_db.execSQL(sql);

            return result;  ///////updated row count??
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return result;
    }

Of course, I can use update() and changes() function. But I want use execSQL() function.

Can I get the count of updated rows by using execSQL() function?

Upvotes: 2

Views: 2103

Answers (2)

CL.
CL.

Reputation: 180020

In the SQLite C API, after a program has executed an UPDATE statement, the number of changed rows can be determined by calling sqlite3_changes().

In the Android framework, the only place where sqlite3_changes() is called is the update() method.

If you need to do UPDATEs that are too complex for update(), you have to execute a second query to call the built-in changes() function:

db.execSQL("UPDATE ...");
long changes = DatebaseUtils.longForQuery(db, "SELECT changes()", null);

Alternatively, you can enable the deprecated PRAGMA count_changes (hoping that it is available) to return the number from the UPDATE statement itself as if it were a query:

class MyOpenHelper {
    ...
    void onConfigure(SQLiteDatabase db) {
        db.execSQL("PRAGMA count_changes = ON");
    }
}

...

changes = DatebaseUtils.longForQuery(db, "UPDATE ...", null);

Upvotes: 4

Idee
Idee

Reputation: 1967

    public int getSingleRow(String food_name){
            SQLiteDatabase myDb = getReadableDatabase();
            Cursor cursor = null;
            int value=0;
            try{
                cursor = myDb.rawQuery("SELECT quantity FROM table_food_palate WHERE name=?",new String[]{food_name});
                if (cursor.getCount() >0){
                    cursor.moveToFirst();
                    value = Integer.parseInt(cursor.getString(cursor.getColumnIndex("id")));
//id stands for the column name called id                    
Log.e("TAG","Value has been saved");
                }
                return value;
            } finally {
                cursor.close();
                myDb.close();
            }
        }

That should give you the id of the row u just updated

Upvotes: -1

Related Questions