
A database is a structured way to store, manage, and retrieve data efficiently in an app.
sqlite3 and Creating a Database (Xcode)A database is a structured way to store, manage, and retrieve data efficiently in an app.
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.
Used to interact with SQLite:
sqlite3 in Xcodeimport SQLite3
Since SQLite is in C language:
ProjectName-Bridging-Header.h
Add:
#import <sqlite3.h>
In Xcode:
var db: OpaquePointer?
let fileURL = try! FileManager.default
.urls(for: .documentDirectory, in: .userDomainMask)
.first!
.appendingPathComponent("AppDatabase.sqlite")
if sqlite3_open(fileURL.path, &db) == SQLITE_OK {
print("Database Created Successfully")
} else {
print("Error creating database")
}
CREATE TABLE Users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
age INTEGER
);
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")
}
Database File (AppDatabase.sqlite)
β
Table: Users
β
------------------------
| id | name | age |
------------------------
| 1 | Ali | 20 |
| 2 | Sara | 22 |
Store:
π Data is saved permanently using SQLite
IF NOT EXISTS to avoid errorsSQLITE_OK)sqlite3_open()?SQLite = lightweight local database
Used for offline data storage
Steps:
Data stored in .sqlite file
Used in apps like:
Open this section to view and download past papers
Click on Show Past Papers to load available exam papers.