SQLite.swift 是一個(gè)使用純 Swift 語(yǔ)言封裝 SQLite3 的操作框架。
特性:
簡(jiǎn)單的查詢(xún)和參數(shù)綁定接口
安全、自動(dòng)類(lèi)型數(shù)據(jù)訪(fǎng)問(wèn)
隱式提交和回滾接口
開(kāi)發(fā)者友好的錯(cuò)誤處理和調(diào)試
文檔完善
通過(guò)廣泛測(cè)試
支持全文檢索
支持SQLCipher
示例代碼:
import SQLite let db = try Connection("path/to/db.sqlite3") let users = Table("users") let id = Expression<Int64>("id") let name = Expression<String?>("name") let email = Expression<String>("email") try db.run(users.create { t in t.column(id, primaryKey: true) t.column(name) t.column(email, unique: true) }) // CREATE TABLE "users" ( // "id" INTEGER PRIMARY KEY NOT NULL, // "name" TEXT, // "email" TEXT NOT NULL UNIQUE // ) let insert = users.insert(name <- "Alice", email <- "alice@mac.com") let rowid = try db.run(insert) // INSERT INTO "users" ("name", "email") VALUES ('Alice', 'alice@mac.com') for user in try db.prepare(users) { print("id: \(user[id]), name: \(user[name]), email: \(user[email])") // id: 1, name: Optional("Alice"), email: alice@mac.com } // SELECT * FROM "users" let alice = users.filter(id == rowid) try db.run(alice.update(email <- email.replace("mac.com", with: "me.com"))) // UPDATE "users" SET "email" = replace("email", 'mac.com', 'me.com') // WHERE ("id" = 1) try db.run(alice.delete()) // DELETE FROM "users" WHERE ("id" = 1) db.scalar(users.count) // 0 // SELECT count(*) FROM "users"