I'm developing an eCommerce app and store the data in the database locally, I a button do the insert, but I need to check if the product is already added into cart or not.
How can I achieve this?
This is my table:
public static final String CREATE_TABLE =
"CREATE TABLE " + TABLE_NAME + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_PRODUCT_ID + " TEXT,"
+ COLUMN_NAME + " TEXT,"
+ COLUMN_MAIN_IMAGE + " TEXT,"
+ COLUMN_MRP_PRICE + " INTEGER , "
+ COLUMN_DISCOUNT_PRICE + " INTEGER , "
+ COLUMN_QUANTITY + " INTEGER" +")";
This is my insert query:
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(OneProductModel.COLUMN_PRODUCT_ID,_id);
values.put(OneProductModel.COLUMN_NAME,name);
values.put(OneProductModel.COLUMN_MAIN_IMAGE,main_image);
values.put(OneProductModel.COLUMN_MRP_PRICE,mrp_price);
values.put(OneProductModel.COLUMN_DISCOUNT_PRICE,discounted_amount);
values.put(OneProductModel.COLUMN_QUANTITY,quantity);
long id = db.insert(OneProductModel.TABLE_NAME,null,values);
db.close();
return id;
One solution would be to make the product id ( COLUMN_PRODUCT_ID ) UNIQUE by using :-
public static final String CREATE_TABLE =
"CREATE TABLE " + TABLE_NAME + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_PRODUCT_ID + " TEXT UNIQUE,"
+ COLUMN_NAME + " TEXT,"
+ COLUMN_MAIN_IMAGE + " TEXT,"
+ COLUMN_MRP_PRICE + " INTEGER , "
+ COLUMN_DISCOUNT_PRICE + " INTEGER , "
+ COLUMN_QUANTITY + " INTEGER" +")";
As such if an attempt to INSERT a product with a product id that already exists then a UNIQUE constraint would occur. However, as the SQLiteDatabase 's insert method effectively uses INSERT OR IGNORE the constraint error is ignored as an error, the row is not inserted and -1 will be returned setting id to -1.
To implement the above schema change you would need to DROP the table and have it recreated.
If there is not any current data or the current data can be lost then there are 2 easy ways to implement the change you can either :-
If you have to preserve existing data, then you would probably be best writing and onUpgrade routine that :-
The routine should also utilise the integers (old version and new version) to ensure that the routine is only run for the specific version number change.
With all of the above implemented you can then change the version number.
the above assumes that the table is the cart
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.