ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Mobile Application Development 2
    COMP4126
    Progress0 / 38 topics
    Topics
    1. Creating an iOS App: Understanding Xcode2. Using the Xcode interface builder and objects library3. Understanding view hierarchy and creating a custom app icon4. Outlets, Actions, and Views: Understanding outlets and actions5. Using text fields, buttons, labels, web views, and page controllers6. Using views with subviews and creating views using code7. Using View Controllers: Working with the single view template8. Exploring the app delegate and adding new view controllers9. Transitioning between multiple view controllers using animations10. Application Templates: Tabbar and master detail templates11. The iOS Keyboard: Customizing for different inputs12. Adjusting text field behaviors and dismissing the keyboard13. Detecting keyboard activities with notification center14. Using scroll view and responding to keyboard activities programmatically15. Working with Different iOS Devices (iPhone & iPad): Detecting device hardware16. Dynamically adjusting graphical layouts and creating universal apps17. Using Table Views: Understanding UITableView and UITableViewCell18. Working with UITableView data source and delegate19. Master detail template, drill-down menus, and navigation20. Using property lists for data persistence and creating multi-section tables21. Supporting Screen Rotations: Portrait and landscape modes22. Handling device rotation and forcing specific orientation23. Dynamically adjusting layouts based on rotation24. Working with Databases: Importing sqlite3 and creating a database25. Writing tables, inserting records, and bundling a database with your app26. Checking for database existence and reading/displaying data27. Using Animations & Video: NSTimer class and object transformations28. Rotation, scaling, translation, animating image arrays, and playing video29. Accessing Integrated iOS Apps: Email, Safari, and SMS30. Working with camera and photo library31. Using Web Services: Consuming and parsing XML and JSON32. Integrating Twitter and Facebook with iOS apps33. Working with iOS Maps and Location Services: MapKit and MKMapView34. Getting and displaying user location and directional information35. Displaying map annotations, disclosure buttons, and reverse geocoding36. Working with iCloud37. Working with the Accelerometer: Gyroscope and accelerometer38. Outputting sensor data and using the Shake API
    COMP4126›Checking for database existence and reading/displaying data
    Mobile Application Development 2Topic 26 of 38

    Checking for database existence and reading/displaying data

    4 minread
    665words
    Beginnerlevel

    🗄️ 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 load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time4 min
      Word count665
      Code examples0
      DifficultyBeginner