Skip to content
This repository was archived by the owner on Mar 25, 2020. It is now read-only.

INSERT Operation

Ricky Tobing edited this page Aug 14, 2013 · 6 revisions

DbQuery is using SQLiteDatabase.insert() in the back. However, the API wraps and add more stuffs to the interface.

The following codes are doing the same exact thing - inserting a 'computer' with $100 price tag to table Products

newProductId = db.get("Products")
                        .insert("Name", "Price")  // column names
                        .val("Computer", 100)         // values
                        .query();
...
newProductId = db.get("Products")
                        .insert(new String[]{"Name", "Price"}, new Object[]{"Computer", 100})
                        .query();
...

Note that query() is called to get the newProductId. If you don't care about the returned value, you may not call query() at all.

#Using ContentValues ContentValues is treated as first class citizen in DbQuery. Recall the code:

ContentValues contentValues = new ContentValues();
contentValues.put("Name", "Computer");
contentValues.put("Price", 100);

newProductId = db.get("Products").insert(contentValues).query()

Note that query() is called to get the newProductId. If you don't care about the returned value, you may not call query() at all.

#Using IEntity With IEntity inserting record makes EASY

// let's say you have this class that implement IEntity
public class Product implements IEntity {
   ...
}

...
// somewhere else...
Product product = new Product();
product.setName("Computer");
product.setPrice(100);

newProductId = db.get("Products").insert(product).query();
assertTrue(product.getId() == newProductId);

Note that query() is called to get the newProductId. If you don't care about the returned value, you may not call query() at all.

#Using IEntityList With IEntityList bulk-inserting record makes EASY

// assume you have product list that implements IEntityList<Product>
public class ProductList implements IEntityList<Product> {
   ...
}

...
ProductList productList = new ProductList();
productList.add(new Product("ProductA", 110));
productList.add(new Product("ProductB", 110));
productList.add(new Product("ProductC", 110));
...
int numInserted = db.get("Products").insert(productList).query();
assertTrue(numInserted == 3);

Note that query() is called to get the numInserted . If you don't care about the returned value, you may not call query() at all.

Clone this wiki locally