{"id":163,"date":"2017-04-09T12:53:15","date_gmt":"2017-04-09T12:53:15","guid":{"rendered":"http:\/\/abhiandroid.com\/database\/?p=163"},"modified":"2018-06-06T05:26:46","modified_gmt":"2018-06-06T05:26:46","slug":"operation-sqlite","status":"publish","type":"post","link":"https:\/\/abhiandroid.com\/database\/operation-sqlite.html","title":{"rendered":"Insert, Read, Delete &#038; Update Operation In SQLite"},"content":{"rendered":"<p>Android provides different ways to store data locally so using SQLite is one the way to store data. SQLite is a structure query base database, hence we can say it\u2019s a relation database. Android os has its own implementation to perform CRUD (Create, Read, Update, Delete)operations, so Android provides set of classes available in android.database and android.database.sqlite packages.<\/p>\n<p>While using SQLite there could be two different ways to perform different operations like create, read, update and delete. One writing raw queries and another is using parameterized functions or we can say parametrized queries.<br \/>\n<img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-177\" src=\"\/database\/wp-content\/uploads\/2017\/03\/SQLite-Database-Operations.jpg\" alt=\"SQLite Database Operations\" width=\"694\" height=\"328\" srcset=\"https:\/\/abhiandroid.com\/database\/wp-content\/uploads\/2017\/03\/SQLite-Database-Operations.jpg 694w, https:\/\/abhiandroid.com\/database\/wp-content\/uploads\/2017\/03\/SQLite-Database-Operations-300x142.jpg 300w\" sizes=\"auto, (max-width: 694px) 100vw, 694px\" \/><br \/>\n<span style=\"color: #008000;\"><strong>Create:<\/strong><\/span> Creating a database is very simple in android by using SQLiteOpenHelper class. SQLiteOpenHelper is an abstract class with two abstract methods onCreate(SQLiteDatabase db) and onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) and many more database helpful functions. Whenever we need to create a database we have to extend SQLiteOpenHelper class as follows:<\/p>\n<pre>\/**A helper class to perform database related queries*\/\r\n\r\npublic class SqliteManager extends SQLiteOpenHelper {\r\npublic static final String DATABASE_NAME = \"abhiandroid.db\";\r\npublic static final int version = 1;\r\n \r\npublic SqliteManager(Context context) {\r\n   super(context, DATABASE_NAME, null, version);\r\n  }\r\n\r\n@Override\r\npublic void onCreate(SQLiteDatabase sqLiteDatabase) {\r\n   String dbQuery = \"CREATE TABLE Items (id INTEGER PRIMARY KEY                          \r\n   AUTOINCREMENT,name TEXT, description TEXT)\";\r\n   sqLiteDatabase.execSQL(dbQuery);\r\n  }\r\n\r\n@Override\r\npublic void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {\r\n  }\r\n}<\/pre>\n<p><strong><span style=\"color: #008000;\">onCreate(SQLiteDatabase sqLiteDatabase)<\/span><\/strong> method is called only for once throughout the application lifecycle, it will be called whenever there is first call to getReadableDatabase() or getWritableDatabase() function available in super SQLiteOpenHelper class so SQLiteOpenHelper class call the onCreate() method after creating database and instantiate SQLiteDatabase object. Database name is passed in constructor call.<\/p>\n<p><strong><span style=\"color: #008000;\">onUpgrade(SQLiteDatabase db,int oldVersion, int newVersion)<\/span><\/strong> is only called whenever there is a updation in existing version so to update a version we have to increment the value of version variable passed in the superclass constructor. In onUpgrade method we can write queries to perform whatever action is required. In most example you will see that existing table(s) are being dropped and again onCreate() method is being called to create tables again. But it\u2019s not mandatory to do so it all depends upon your requirements. We have to change database version if we have added a new row in the database table in this case if we have requirement that we don\u2019t want to lost existing data in the table then we can write alter table query in the onUpgrade(SQLiteDatabase db,int oldVersion, int newVersion) method.<\/p>\n<p>Likewise if there is no requirement of existing data whenever we upgrade database version then we can write drop table query in onUpgrade(SQLiteDatabase db,int oldVersion, int newVersion) method and call onCreate(SQLiteDatabase sqLiteDatabase) method again to create table again. Remember never call onCreate(SQLiteDatabase sqLiteDatabase) method if you have written alter table query in onUpgrade(SQLiteDatabase db,int oldVersion, int newVersion) method.<\/p>\n<hr \/>\n<h4><b>Insert, Read, Delete &amp; Update Operation In Sqlite:<\/b><\/h4>\n<p>To perform insert, read, delete, update operation there are two different ways:<\/p>\n<ul>\n<li>Write parameterized queries (Recommended)<\/li>\n<li>Write raw queries<\/li>\n<\/ul>\n<p><b>Parameterized Queries: <\/b>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.<\/p>\n<p><b>Raw Queries: <\/b>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.<\/p>\n<p><span style=\"text-decoration: underline; color: #ff0000;\"><strong>Important Note:<\/strong> <\/span>Android documentation don\u2019t recommend to use raw queries to perform insert, read, update, delete operations, always use SQLiteDatabase class\u2019s insert, query, update, delete functions.<\/p>\n<p>Following is an example of raw query to insert data:<\/p>\n<pre>public void insertItem(Item item) {\r\n  String query = \"INSERT INTO \" + ItemTable.<i>NAME <\/i>+ \" VALUES (0,?,?)\";\r\n  SQLiteDatabase db = getWritableDatabase();\r\n  db.execSQL(query, new String[]{item.name, item.description});\r\n  db.close();\r\n}<\/pre>\n<p>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.<\/p>\n<p><span style=\"color: #008000;\"><b>Insert:\u00a0<\/b><\/span>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 \u00a0nullColumnHack,ContentValues values) where tableName is name of table in which data to be inserted.<\/p>\n<pre>public long insert(String tableName,String \u00a0nullColumnHack,ContentValues values)<\/pre>\n<p>NullColumnHack may be passed null, it require table column value in case we don\u2019t put column name in ContentValues object so a null value must be inserted for that particular column, values are those values that needs to be inserted- ContentValues is a key-pair based object which accepts all primitive type values so whenever data is being put in ContentValues object it should be put again table column name as key and data as value. insert function will return a long value i.e number of inserted row if successfully inserted, &#8211; 1 otherwise.<\/p>\n<p><strong>Here is simple example:<\/strong><\/p>\n<pre>\/\/Item is a class representing any item with id, name and description.\r\npublic void addItem(Item item) {\r\n  SQLiteDatabase db = getWritableDatabase();\r\n  ContentValues contentValues = new ContentValues();\r\n  contentValues.put(\"name\",item.name);\r\n   \/\/ name - column\r\n   contentValues.put(\"description\",item.description);\r\n   \/\/ description is column in items table, item.description has value for description\r\n  db.insert(\"Items\", null, contentValues);\/\/Items is table name\r\n   db.close();\r\n}<\/pre>\n<p><span style=\"color: #008000;\"><strong>Update<\/strong>:\u00a0<\/span>Update function is quite similar to insert but it requires two additional parameters, it doesn\u2019t required nullColumnHack. It has total four parameters two are similar to insert function that is tableName and contentValues. Another two are whereClause(String) and whereArgs(String[]).<\/p>\n<p>Update function is available in SQLiteDatabase class it looks as follows:<\/p>\n<pre>public int update(String tableName,ContentValues contentValues,String whereClause,String[] whereArgs)\r\n<\/pre>\n<p>Here whereClause is tell the database where to update data in table, it\u2019s recommended to pass ?s (questions) along with column name in whereClause String. Similarly whereArgs array will contain values for those columns whose against ?s has been put in whereClause. Update function will return number of rows affected if success, 0 otherwise.<\/p>\n<p><strong>Here is simple use of update:<\/strong><\/p>\n<pre>\/\/Item is a class representing any item with id, name and description\r\npublic void updateItem(Item item) {\r\n  SQLiteDatabase db = getWritableDatabase();\r\n  ContentValues contentValues = new ContentValues();\r\n  contentValues.put(\"id\", item.id);\r\n  contentValues.put(\"name\", item.name);\r\n  contentValues.put(\"description\", item.description);\r\n  String whereClause = \"id=?\";\r\n  String whereArgs[] = {item.id.toString()};\r\n  db.update(\"Items\", contentValues, whereClause, whereArgs);\r\n}<\/pre>\n<p><b><span style=\"color: #008000;\">Delete:<\/span> <\/b>Similar to insert and update, delete function is available in SQLiteDatabase class, So delete is very similar to update function apart from ContentValues object as it\u2019s not required in delete. public int delete(String tableName,String whereClause,String [] whereArgs) function has three parameters these are totally similar to update function\u2019s parameters and are used in same way as in update function.<\/p>\n<p><strong>Here is simple use of delete:<\/strong><\/p>\n<pre><b>public void <\/b>deleteItem(Item item) {\r\nSQLiteDatabase db = getWritableDatabase();\r\nString whereClause = <b>\"id=?\"<\/b>;\r\nString whereArgs[] = {item.<b>id<\/b>.toString()};\r\ndb.delete(<b>\"Items\"<\/b>, whereClause, whereArgs);\r\n}<\/pre>\n<p>Here whereClause is optional, passing null will delete all rows in table. delete function will return number of affected row if whereClause passed otherwise will return 0.<\/p>\n<p><span style=\"text-decoration: underline; color: #ff0000;\"><b>Important Note: <\/b><\/span>If you want to remove all rows and require count of deleted ones also then pass 1 as whereClause.<\/p>\n<p><b><span style=\"color: #008000;\">Read(select):<\/span> <\/b>Reading from a database table is bit different from other functions like insert,update and delete. SQLiteDatabase class provides <span style=\"color: #008000;\">query()<\/span> method to read data from table. query() method is overloaded with different set of parameters. It returns <em>Cursor<\/em> object so Cursor is a result-set with queried data, it provides different functions really helpful while reading data.<\/p>\n<p><strong>Following are some overloaded query functions:<\/strong><\/p>\n<ul>\n<li>public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)<\/li>\n<li>public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)<\/li>\n<li>public Cursor query (boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)<\/li>\n<\/ul>\n<p>Most of the parameters in query overloaded functions are optional except from table and distinct any of other parameters can be passed as null. if distinct is passed as true Cursor data set will not have any duplicate row.<\/p>\n<pre>public ArrayList&lt;Item&gt; readAllItems() {\r\nArrayList&lt;Item&gt; items = new ArrayList&lt;&gt;();\r\nSQLiteDatabase db = getReadableDatabase();\r\n\/\/see above point 2 function\r\nCursor cursor = db.query(\"Items\"\r\n, null\/\/ columns - null will give all\r\n, null\/\/ selection \r\n, null\/\/ selection arguments\r\n, null\/\/ groupBy\r\n, null\/\/ having \r\n, null\/\/ no need or order by for now;\r\nif (cursor != null) {\r\n  while (cursor.moveToNext()) {\r\n  \/\/ move the cursor to next row if there is any to read it's data\r\n \u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0Item item = readItem(cursor);\r\n           items.add(item);\r\n     }\r\n  }\r\nreturn items;\r\n}\r\n\r\nprivate Item readItem(Cursor cursor) {\r\n  Item item = new Item();\r\n  item.id = cursor.getInt(cursor.getColumnIndex(ItemTable.<i>COL_ID<\/i>));\r\n  item.name = cursor.getString(cursor.getColumnIndex(ItemTable.<i>COL_NAME<\/i>));\r\n  item.description = cursor.getString(cursor.getColumnIndex(ItemTable.<i>COL_DESCRIPTION<\/i>));\r\n  return item;\r\n}<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Android provides different ways to store data locally so using SQLite is one the way to store data. SQLite is a structure query base database, hence we can say it\u2019s a relation database. Android os has its own implementation to perform CRUD (Create, Read, Update, Delete)operations, so Android provides set of classes available in android.database &hellip; <a href=\"https:\/\/abhiandroid.com\/database\/operation-sqlite.html\" class=\"more-link\">Continue reading <span class=\"screen-reader-text\">Insert, Read, Delete &#038; Update Operation In SQLite<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[1],"tags":[],"class_list":["post-163","post","type-post","status-publish","format-standard","hentry","category-archive"],"acf":[],"psp_head":"<title>Insert, Read, Delete &amp; Update Operations In SQLite With Example For Android \u2013 Android Database Tutorial In Android Studio: Store Your Data<\/title>\r\n<meta name=\"description\" content=\"Understand different ways to use insert, read, delete and update operation in SQlite with example. Android os has its own implementation to perform CRUD (Create, Read, Update, Delete)operations, so Android provides set of classes available in android.database and android.database.sqlite packages.\" \/>\r\n<meta name=\"robots\" content=\"index,follow\" \/>\r\n<link rel=\"canonical\" href=\"https:\/\/abhiandroid.com\/database\/operation-sqlite.html\" \/>\r\n","_links":{"self":[{"href":"https:\/\/abhiandroid.com\/database\/wp-json\/wp\/v2\/posts\/163","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/abhiandroid.com\/database\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/abhiandroid.com\/database\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/abhiandroid.com\/database\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/abhiandroid.com\/database\/wp-json\/wp\/v2\/comments?post=163"}],"version-history":[{"count":1,"href":"https:\/\/abhiandroid.com\/database\/wp-json\/wp\/v2\/posts\/163\/revisions"}],"predecessor-version":[{"id":322,"href":"https:\/\/abhiandroid.com\/database\/wp-json\/wp\/v2\/posts\/163\/revisions\/322"}],"wp:attachment":[{"href":"https:\/\/abhiandroid.com\/database\/wp-json\/wp\/v2\/media?parent=163"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/abhiandroid.com\/database\/wp-json\/wp\/v2\/categories?post=163"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/abhiandroid.com\/database\/wp-json\/wp\/v2\/tags?post=163"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}