
It means verifying whether the SQLite database file already exists in the device storage before creating or copying it.
It means verifying whether the SQLite database file already exists in the device storage before creating or copying it.
It means retrieving stored records from a database using the SQL SELECT statement.
It means showing retrieved database records in the UI, usually in a:
let fileManager = FileManager.default
let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
let dbPath = documentsURL.appendingPathComponent("AppDatabase.sqlite")
if fileManager.fileExists(atPath: dbPath.path) {
print("Database exists")
} else {
print("Database does not exist")
}
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")
}
var db: OpaquePointer?
if sqlite3_open(dbPath.path, &db) == SQLITE_OK {
print("Database opened successfully")
}
SELECT * FROM Students;
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)
var names: [String] = []
var ages: [Int] = []
names.append(name)
ages.append(Int(age))
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return names.count
}
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
}
Database (SQLite)
β
SELECT Query
β
Swift Variables (Arrays)
β
UITableView
β
Screen Display
π Output:
sqlite3_finalize()tableView.reloadData()
sqlite3_step() used for?SELECT query to read datasqlite3_step() to iterate rowsOpen this section to view and download past papers
Click on Show Past Papers to load available exam papers.