Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between inserting data using ContentValues and Raw SQL in SQLite Android?

I want to know the difference between inserting data using ContentValues and inserting data using Raw SQL in SQLlite(Android), Is there a advantage using content values?

like image 344
M Monis Ahmed Khan Avatar asked May 25 '26 01:05

M Monis Ahmed Khan


1 Answers

To perform insert, read, delete, update operation there are two different ways:

  1. Write parameterized queries (Recommended)
  2. Write raw queries

Parameterized Queries: These are those queries which are performed using inbuilt functions to insert, read, delete or update data. These operation related functions are provided in SQLiteDatabase class.

Raw Queries: These are simple sql queries similar to other databases like MySql, Sql Server etc, In this case user will have to write query as text and passed the query string in rawQuery(String sql,String [] selectionArgs) or execSQL(String sql,Object [] bindArgs) method to perform operations.

Important Note: Android documentation don’t recommend to use raw queries to perform insert, read, update, delete operations, always use SQLiteDatabase class’s insert, query, update, delete functions.

Following is an example of raw query to insert data:

public void insertItem(Item item) {
  String query = "INSERT INTO " + ItemTable.NAME + " VALUES (0,?,?)";
  SQLiteDatabase db = getWritableDatabase();
  db.execSQL(query, new String[]{item.name, item.description});
  db.close();
}

While using raw queries we never come to know the result of operation, however with parameterized queries function a value is returned for success or failure of operation.

Insert: To perform insert operation using parameterized query we have to call insert function available in SQLiteDatabase class. insert() function has three parameters like public long insert(String tableName,String nullColumnHack,ContentValues values) where tableName is name of table in which data to be inserted.

Here is simple example:

//Item is a class representing any item with id, name and description.
public void addItem(Item item) {
  SQLiteDatabase db = getWritableDatabase();
  ContentValues contentValues = new ContentValues();
  contentValues.put("name",item.name);
   // name - column
   contentValues.put("description",item.description);
   // description is column in items table, item.description has value for description
   db.insert("Items", null, contentValues);//Items is table name
   db.close();
}

For more Information see this Link

like image 109
rafsanahmad007 Avatar answered May 26 '26 14:05

rafsanahmad007



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!