Using SQLite directly from Swift is a straightforward process that allows developers to manage local databases seamlessly within their applications. SQLite is an embedded database engine that is light and easy to integrate. Below is an example of how to set up and use SQLite in a Swift application.
import SQLite3
class Database {
var db: OpaquePointer?
init?() {
// Open database
if sqlite3_open("myDatabase.sqlite", &db) != SQLITE_OK {
print("Error opening database")
return nil
}
createTable()
}
func createTable() {
let createTableString = "CREATE TABLE IF NOT EXISTS contacts (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, phone TEXT);"
var createTableStatement: OpaquePointer? = nil
if sqlite3_prepare_v2(db, createTableString, -1, &createTableStatement, nil) == SQLITE_OK {
if sqlite3_step(createTableStatement) == SQLITE_DONE {
print("Contacts table created.")
} else {
print("Contacts table could not be created.")
}
}
sqlite3_finalize(createTableStatement)
}
deinit {
sqlite3_close(db)
}
}
let database = Database()
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?