ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCOMP4126Databases Sqlite3 Crea…
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    COMP4126

    Mobile Application Development 2

    Progress0 / 38 done
    Topics38
    1Understanding Xcode2Using the Xcode interface builder and objects library3Understanding view hierarchy and creating a custom app icon
    4Understanding outlets and actions5Using text fields, buttons, labels, web views, and page controllers6Using views with subviews and creating views using code
    7Working with the single view template8Exploring the app delegate and adding new view controllers9Transitioning between multiple view controllers using animations
    10Tabbar and master detail templates
    11Customizing for different inputs12Adjusting text field behaviors and dismissing the keyboard13Detecting keyboard activities with notification center14Using scroll view and responding to keyboard activities programmatically
    15Detecting device hardware16Dynamically adjusting graphical layouts and creating universal apps
    17Understanding UITableView and UITableViewCell18Working with UITableView data source and delegate19Master detail template, drill-down menus, and navigation20Using property lists for data persistence and creating multi-section tables
    21Portrait and landscape modes22Handling device rotation and forcing specific orientation23Dynamically adjusting layouts based on rotation
    24Importing sqlite3 and creating a database25Writing tables, inserting records, and bundling a database with your app26Checking for database existence and reading/displaying data
    27NSTimer class and object transformations28Rotation, scaling, translation, animating image arrays, and playing video
    29Email, Safari, and SMS30Working with camera and photo library
    31Consuming and parsing XML and JSON32Integrating Twitter and Facebook with iOS apps
    33MapKit and MKMapView34Getting and displaying user location and directional information35Displaying map annotations, disclosure buttons, and reverse geocoding36Working with iCloud
    37Gyroscope and accelerometer38Outputting sensor data and using the Shake API
    3 min read
    Topic 24 of 38
    Topic Study Note Illustration
    24

    Working with Databases: Importing sqlite3 and creating a database

    A database is a structured way to store, manage, and retrieve data efficiently in an app.

    πŸ—„οΈ Working with Databases in iOS: Importing sqlite3 and Creating a Database (Xcode)


    βœ… 1. Definition

    πŸ”Ή Database

    A database is a structured way to store, manage, and retrieve data efficiently in an app.

    πŸ”Ή SQLite (sqlite3)

    SQLite is a lightweight, embedded relational database used in iOS apps. It stores data in a single file on the device.

    πŸ‘‰ In simple words: SQLite allows iOS apps to save data permanently offline.


    🧠 2. Key Concepts

    πŸ”Ή SQLite Features

    • Lightweight (small size)
    • Fast performance
    • No server required
    • Stored locally on device

    πŸ”Ή SQL (Structured Query Language)

    Used to interact with SQLite:

    • CREATE β†’ create table
    • INSERT β†’ add data
    • SELECT β†’ read data
    • UPDATE β†’ modify data
    • DELETE β†’ remove data

    πŸ”Ή sqlite3 Library

    • Built-in C library for SQLite
    • Used in iOS via bridging header

    βš™οΈ 3. Importing sqlite3 in Xcode


    πŸ”Ή Step 1: Import Library

    import SQLite3
    

    πŸ”Ή Step 2: Add Bridging Header (Important)

    Since SQLite is in C language:

    Create bridging header file:

    ProjectName-Bridging-Header.h
    

    Add:

    #import <sqlite3.h>
    

    πŸ”Ή Step 3: Enable Bridging Header

    In Xcode:

    • Build Settings β†’ Objective-C Bridging Header
    • Add path to header file

    πŸ—οΈ 4. Creating a Database


    πŸ”Ή Step 1: Declare Database Variable

    var db: OpaquePointer?
    

    πŸ”Ή Step 2: Create Database File

    let fileURL = try! FileManager.default
        .urls(for: .documentDirectory, in: .userDomainMask)
        .first!
        .appendingPathComponent("AppDatabase.sqlite")
    

    πŸ”Ή Step 3: Open Database

    if sqlite3_open(fileURL.path, &db) == SQLITE_OK {
        print("Database Created Successfully")
    } else {
        print("Error creating database")
    }
    

    🧱 5. Creating a Table


    πŸ”Ή SQL Query Example

    CREATE TABLE Users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT,
        age INTEGER
    );
    

    πŸ”Ή Swift Code to Execute Query

    let createTableQuery = """
    CREATE TABLE IF NOT EXISTS Users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT,
    age INTEGER
    );
    """
    
    if sqlite3_exec(db, createTableQuery, nil, nil, nil) == SQLITE_OK {
        print("Table Created")
    } else {
        print("Table Creation Failed")
    }
    

    πŸ“Š 6. Database Structure Diagram (for Exams)

    Database File (AppDatabase.sqlite)
            ↓
       Table: Users
            ↓
    ------------------------
    | id | name | age     |
    ------------------------
    | 1  | Ali  | 20      |
    | 2  | Sara | 22      |
    

    πŸ’‘ 7. Example App

    🎯 Student Management App

    • Store:

      • ID
      • Name
      • Age

    πŸ‘‰ Data is saved permanently using SQLite


    πŸ“Œ 8. Important Rules / Tips

    • Always open database before using it
    • Use IF NOT EXISTS to avoid errors
    • Store database in Documents directory
    • Close database after use (good practice)
    • Use prepared statements for security

    ⚠️ 9. Common Mistakes

    • ❌ Forgetting to import sqlite3
    • ❌ Not setting bridging header
    • ❌ Wrong file path for database
    • ❌ Not checking execution success
    • ❌ Using hardcoded SQL without validation

    🧠 10. Best Practices

    • Always check return status (SQLITE_OK)
    • Use prepared statements for safety
    • Keep database schema simple
    • Store DB in Documents directory
    • Close DB when not needed

    πŸ“ 11. Likely Exam Questions

    1. What is SQLite in iOS?
    2. How do you import sqlite3 in Xcode?
    3. What is a bridging header?
    4. Write steps to create a database in iOS.
    5. What is the use of sqlite3_open()?
    6. Write SQL query to create a table.
    7. Why is SQLite used in mobile apps?
    8. Draw database structure diagram.

    πŸ“š 12. Quick Revision Summary

    • SQLite = lightweight local database

    • Used for offline data storage

    • Steps:

      1. Import sqlite3
      2. Create bridging header
      3. Open database
      4. Create tables
    • Data stored in .sqlite file

    • Used in apps like:

      • Students apps
      • Notes apps
      • Inventory systems

    ← Previous topic 23
    Dynamically adjusting layouts based on rotation
    Next topic 25 β†’
    Writing tables, inserting records, and bundling a database with your app

    Past Papers

    Open this section to view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    3mremaining
    577words
    Beginnerlevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Mobile Application Development 2