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 PortalCOMP4126Database Tables Insert…
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
    4 min read
    Topic 25 of 38
    Topic Study Note Illustration
    25

    Writing tables, inserting records, and bundling a database with your app

    Creating a table in SQLite means defining a structure to store data in rows and columns.

    πŸ—„οΈ SQLite in iOS: Writing Tables, Inserting Records & Bundling a Database with Your App (Xcode)


    βœ… 1. Definition

    πŸ”Ή Writing Tables

    Creating a table in SQLite means defining a structure to store data in rows and columns.


    πŸ”Ή Inserting Records

    Adding actual data (rows) into a database table using SQL INSERT.


    πŸ”Ή Bundling Database with App

    It means including a pre-created SQLite database inside the app bundle, so the app can use it immediately when installed.


    🧠 2. Key Concepts

    πŸ”Ή Table Structure

    A table contains:

    • Columns (fields) β†’ name, age, id
    • Rows (records) β†’ actual data

    πŸ”Ή SQL Commands Used

    Operation SQL Command
    Create Table CREATE
    Insert Data INSERT
    Read Data SELECT

    πŸ”Ή App Bundle

    • Read-only location inside the app
    • Cannot modify files directly inside bundle
    • Database must be copied to Documents folder for editing

    πŸ—οΈ 3. Writing a Table in SQLite


    πŸ”Ή SQL Query to Create Table

    CREATE TABLE IF NOT EXISTS Students (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT,
        age INTEGER
    );
    

    πŸ”Ή Swift Code

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

    βž• 4. Inserting Records into Table


    πŸ”Ή SQL Insert Query

    INSERT INTO Students (name, age)
    VALUES ('Ali', 20);
    

    πŸ”Ή Swift Code for Insert

    let insertQuery = "INSERT INTO Students (name, age) VALUES ('Ali', 20);"
    
    if sqlite3_exec(db, insertQuery, nil, nil, nil) == SQLITE_OK {
        print("Record Inserted Successfully")
    } else {
        print("Insert Failed")
    }
    

    πŸ”Ή Dynamic Insert (Recommended)

    var stmt: OpaquePointer?
    
    let query = "INSERT INTO Students (name, age) VALUES (?, ?)"
    
    if sqlite3_prepare_v2(db, query, -1, &stmt, nil) == SQLITE_OK {
        
        sqlite3_bind_text(stmt, 1, "Sara", -1, nil)
        sqlite3_bind_int(stmt, 2, 22)
        
        if sqlite3_step(stmt) == SQLITE_DONE {
            print("Data inserted")
        }
    }
    
    sqlite3_finalize(stmt)
    

    πŸ“Š 5. Database Table Diagram (for Exams)

    Table: Students
    -------------------------
    | id | name | age      |
    -------------------------
    | 1  | Ali  | 20       |
    | 2  | Sara | 22       |
    -------------------------
    

    πŸ“¦ 6. Bundling SQLite Database with App


    πŸ”Ή Step 1: Add Database File

    • Drag .sqlite file into Xcode project
    • Select Copy items if needed

    πŸ”Ή Step 2: Access Database from Bundle

    let bundlePath = Bundle.main.path(forResource: "AppDatabase", ofType: "sqlite")
    

    πŸ”Ή Step 3: Copy to Documents Directory (Important)

    πŸ‘‰ Bundle is read-only, so we copy database:

    let fileManager = FileManager.default
    
    let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
    let destPath = documentsURL.appendingPathComponent("AppDatabase.sqlite")
    
    if !fileManager.fileExists(atPath: destPath.path) {
        try fileManager.copyItem(atPath: bundlePath!, toPath: destPath.path)
        print("Database copied to Documents folder")
    }
    

    πŸ”Ή Step 4: Use Copied Database

    sqlite3_open(destPath.path, &db)
    

    πŸ’‘ 7. Example App

    🎯 Student Management App

    • Preloaded database contains student list

    • App copies database on first launch

    • Users can:

      • View students
      • Add new students
      • Store data permanently

    πŸ“Œ 8. Important Rules / Tips

    • Always copy bundled DB to Documents directory
    • Use IF NOT EXISTS when creating tables
    • Use prepared statements for safe insertion
    • Close database after operations
    • Keep schema simple and structured

    ⚠️ 9. Common Mistakes

    • ❌ Trying to modify database inside app bundle
    • ❌ Forgetting to copy database to Documents folder
    • ❌ Not checking SQL execution success
    • ❌ Using unsafe direct string queries
    • ❌ Incorrect table structure

    🧠 10. Best Practices

    • Always use prepared statements
    • Validate user input before inserting
    • Store database in Documents directory
    • Keep backup of initial database in bundle
    • Use meaningful table/column names

    πŸ“ 11. Likely Exam Questions

    1. What is SQLite used for in iOS?
    2. Write SQL query to create a table.
    3. How do you insert records in SQLite?
    4. What is a bundled database?
    5. Why do we copy database from bundle to Documents folder?
    6. Write Swift code for inserting data.
    7. Explain structure of SQLite table.
    8. What is the use of sqlite3_prepare_v2()?

    πŸ“š 12. Quick Revision Summary

    • Tables store structured data (rows & columns)
    • Use CREATE TABLE to define structure
    • Use INSERT to add records
    • Bundled DB = preloaded database inside app
    • Must copy DB to Documents for writing
    • SQLite used for offline data storage
    • Essential for student, notes, inventory apps

    ← Previous topic 24
    Working with Databases: Importing sqlite3 and creating a database
    Next topic 26 β†’
    Checking for database existence and reading/displaying data

    Past Papers

    Open this section to view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    4mremaining
    722words
    Beginnerlevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Mobile Application Development 2