mercredi 9 mars 2016

Insert query not working as expected in android sqlite

This is my create table query.

String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_BRANDS + "("
    + KEY_ID + " INTEGER UNIQUE,"
    + KEY_NAME + " TEXT UNIQUE,"
    + KEY_CREATED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,"
    + KEY_UPDATED_AT + " TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP" + ")";

db.execSQL(CREATE_CONTACTS_TABLE);

This is function for updating/adding new brand.

void addBrand(Brand brand) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_ID, brand.getId()); // Contact Name
    values.put(KEY_NAME, brand.getName()); // Contact Name


    db.execSQL("UPDATE " + TABLE_BRANDS +
                    " SET " + KEY_NAME + " = ?, " +
                    KEY_UPDATED_AT + " = CURRENT_TIMESTAMP" +
                    " WHERE " + KEY_ID + " = ?",
            new Object[]{brand.getName(), brand.getId()});


    db.insertWithOnConflict(TABLE_BRANDS, null, values, SQLiteDatabase.CONFLICT_IGNORE);        
    db.close(); // Closing database connection
}

while calling i am passing id and name explicitly like this.

db.addBrand(new Brand(17, "sdddddsfsfdsfdshfjdh"));

The problem is addBrand () is not adding brand_id, that i am passing. It is adding a sequential value (1, 2 3 4) instead of that??

Why is this behaviour? How to fix that?

As per my understanding if i am not having a column with primary key sqlite will add a column its own to identify row. Am i wrong?

Aucun commentaire:

Enregistrer un commentaire