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 Existence Rea…
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 26 of 38
    Topic Study Note Illustration
    26

    Checking for database existence and reading/displaying data

    It means verifying whether the SQLite database file already exists in the device storage before creating or copying it.

    πŸ—„οΈ Checking Database Existence & Reading/Displaying Data in SQLite (iOS – Xcode)


    βœ… 1. Definition

    πŸ”Ή Database Existence Check

    It means verifying whether the SQLite database file already exists in the device storage before creating or copying it.


    πŸ”Ή Reading Data

    It means retrieving stored records from a database using the SQL SELECT statement.


    πŸ”Ή Displaying Data

    It means showing retrieved database records in the UI, usually in a:

    • UITableView
    • UILabel
    • Custom views

    🧠 2. Key Concepts

    πŸ”Ή FileManager

    • Used to check if database file exists in device storage

    πŸ”Ή SQLite SELECT Query

    • Used to fetch data from tables

    πŸ”Ή Prepared Statement

    • Secure way to read data from SQLite

    πŸ“ 3. Checking Database Existence


    πŸ”Ή Step 1: Define Database Path

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

    πŸ”Ή Step 2: Check If File Exists

    if fileManager.fileExists(atPath: dbPath.path) {
        print("Database exists")
    } else {
        print("Database does not exist")
    }
    

    πŸ”Ή Step 3: Copy from Bundle (If Needed)

    if !fileManager.fileExists(atPath: dbPath.path) {
        let bundlePath = Bundle.main.path(forResource: "AppDatabase", ofType: "sqlite")
        
        try fileManager.copyItem(atPath: bundlePath!, toPath: dbPath.path)
        
        print("Database copied")
    }
    

    πŸ“– 4. Opening Database

    var db: OpaquePointer?
    
    if sqlite3_open(dbPath.path, &db) == SQLITE_OK {
        print("Database opened successfully")
    }
    

    πŸ“Š 5. Reading Data from Database


    πŸ”Ή SQL SELECT Query

    SELECT * FROM Students;
    

    πŸ”Ή Swift Code to Read Data

    let query = "SELECT * FROM Students"
    
    var stmt: OpaquePointer?
    
    if sqlite3_prepare_v2(db, query, -1, &stmt, nil) == SQLITE_OK {
        
        while sqlite3_step(stmt) == SQLITE_ROW {
            
            let id = sqlite3_column_int(stmt, 0)
            
            let name = String(cString: sqlite3_column_text(stmt, 1))
            
            let age = sqlite3_column_int(stmt, 2)
            
            print("ID: \(id), Name: \(name), Age: \(age)")
        }
    }
    
    sqlite3_finalize(stmt)
    

    πŸ“Ί 6. Displaying Data in UITableView


    πŸ”Ή Step 1: Create Arrays

    var names: [String] = []
    var ages: [Int] = []
    

    πŸ”Ή Step 2: Store Data from Database

    names.append(name)
    ages.append(Int(age))
    

    πŸ”Ή Step 3: Table View Methods

    Number of Rows

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return names.count
    }
    

    Display Data

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
        let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cell")
        
        cell.textLabel?.text = names[indexPath.row]
        cell.detailTextLabel?.text = "Age: \(ages[indexPath.row])"
        
        return cell
    }
    

    πŸ“Š 7. Data Flow Diagram (for Exams)

    Database (SQLite)
          ↓
    SELECT Query
          ↓
    Swift Variables (Arrays)
          ↓
    UITableView
          ↓
    Screen Display
    

    πŸ’‘ 8. Example App

    🎯 Student List App

    • Check database exists
    • Load student records
    • Display in table view

    πŸ‘‰ Output:

    • Ali – 20
    • Sara – 22
    • Ahmed – 21

    πŸ“Œ 9. Important Rules / Tips

    • Always check database existence before opening
    • Use Documents directory for writable DB
    • Finalize statements using sqlite3_finalize()
    • Store data in arrays before displaying
    • Reload table view after fetching data
    tableView.reloadData()
    

    ⚠️ 10. Common Mistakes

    • ❌ Not checking database existence
    • ❌ Using bundle database directly for writing
    • ❌ Forgetting to finalize statement
    • ❌ Not handling empty results
    • ❌ Crashing due to nil database path

    🧠 11. Best Practices

    • Always use FileManager for existence check
    • Separate database logic from UI
    • Use arrays or models for clean data handling
    • Reload UI after data fetch
    • Handle errors properly

    πŸ“ 12. Likely Exam Questions

    1. How do you check if a database exists in iOS?
    2. What is the use of FileManager?
    3. Write SQL query to read all records.
    4. Explain how data is fetched from SQLite.
    5. How do you display database data in UITableView?
    6. What is sqlite3_step() used for?
    7. Why do we use Documents directory?
    8. Draw a diagram of database data flow.

    πŸ“š 13. Quick Revision Summary

    • Check DB existence using FileManager
    • If not found β†’ copy from bundle
    • Use SELECT query to read data
    • Use sqlite3_step() to iterate rows
    • Store data in arrays
    • Display using UITableView
    • Always reload UI after fetching data

    ← Previous topic 25
    Writing tables, inserting records, and bundling a database with your app
    Next topic 27 β†’
    Using Animations & Video: NSTimer class and object transformations

    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
    665words
    Beginnerlevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Mobile Application Development 2