Creating a table in SQLite means defining a structure to store data in rows and columns.
Adding actual data (rows) into a database table using SQL INSERT.
It means including a pre-created SQLite database inside the app bundle, so the app can use it immediately when installed.
A table contains:
| Operation | SQL Command |
|---|---|
| Create Table | CREATE |
| Insert Data | INSERT |
| Read Data | SELECT |
CREATE TABLE IF NOT EXISTS Students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
age INTEGER
);
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")
}
INSERT INTO Students (name, age)
VALUES ('Ali', 20);
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")
}
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)
Table: Students
-------------------------
| id | name | age |
-------------------------
| 1 | Ali | 20 |
| 2 | Sara | 22 |
-------------------------
.sqlite file into Xcode projectlet bundlePath = Bundle.main.path(forResource: "AppDatabase", ofType: "sqlite")
👉 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")
}
sqlite3_open(destPath.path, &db)
Preloaded database contains student list
App copies database on first launch
Users can:
IF NOT EXISTS when creating tablessqlite3_prepare_v2()?CREATE TABLE to define structureINSERT to add recordsOpen this section to load past papers