Lecture 8: Database Topics: Basic SQLite Operations
Today’s class: Concepts Database, Table, Primary Key (Lecture) SQL Commands Android (code) Example of “Characters” database Create, Insert, Delete, Query
Database Bunch of tables having column headers where you store data—one datum in each row. Table: Characters Table: Appearance ID Name Home 1 John Winterfell 2 Tyrion Casterly Rock 3 Daenerys Dragon Stone Episode CharacterID Appeared 1 10 2 5 3 7 9 Power manage: wake lock, reboot.
Create and Drop Tables SQL: CREATE TABLE Characters ( ID INT PRIMARY KEY, NAME TEXT, HOME TEXT ); Table: Characters ID Name Home SQL: Power manage: wake lock, reboot. DROP TABLE IF EXISTS Characters;
Insert and Delete Rows SQL: Table: Characters INSERT INTO Characters VALUES (1, ‘John’, ‘Winterfell’); VALUES (2, ‘Tyrion’, ‘Casterly Rock’); ID Name Home 1 John Winterfell 2 Tyrion Casterly Rock SQL: Table: Characters DELETE FROM Characters WHERE Name = ‘John’; ID Name Home 2 Tyrion Casterly Rock Power manage: wake lock, reboot.
Query SELECT * FROM Characters WHERE ID < 3; SQL: Table: Characters SELECT * FROM Characters WHERE ID < 3; ID Name Home 1 John Winterfell 2 Tyrion Casterly Rock 3 Daenerys Dragon Stone SQL: Table: Characters SELECT Name, Episode, Appeared FROM Characters, Appearance WHERE ID = CharacterID AND Episode = 1 AND Appeared < 7 ID Name Home Power manage: wake lock, reboot.
Query SELECT Name, Episode, Appeared FROM Characters, Appearance Table: Characters SQL: ID Name Home 1 John Winterfell 2 Tyrion Casterly Rock 3 Daenerys Dragon Stone SELECT Name, Episode, Appeared FROM Characters, Appearance WHERE ID = CharacterID AND Episode = 1 AND Appeared < 7 Table: Appearance Episode CharacterID Appeared 1 10 2 5 3 7 9 Output: Power manage: wake lock, reboot. Name Episode Appeared Tyrion 1 5
Android SQLite (in 3 lines) What? How? Database Open/Create SQLiteDatabase db = this.openOrCreateDatabase (“SomeDB", Context.MODE_PRIVATE, null); Table Drop/Create Rows Insert/delete db.execSQL(“A SQL COMMAND”); Select Cursor c = db.rawQuery("SELECT …. “); c.moveToFirst(); c.getString(index); c.moveToNext(); Power manage: wake lock, reboot.
References (study these) https://developer.android.com/training/basics/data-storage/databases.html