SQLite.swift —— 安全、高效的Swift数据库解决方案
SQLite.swift 是一个纯Swift编写的SQLite3接口层,它提供了类型安全和可选匹配的SQL表达式构建器,让开发人员在编译阶段就能检查SQL语句的语法和意图。
特性
- 纯Swift实现
- 类型安全的SQL表达式构造器
- 灵活、链式查询执行层
- 自动类型数据访问
- 轻量级、简单的查询和参数绑定接口
- 开发者友好的错误处理和调试工具
- 支持全文搜索
- 内部详细文档
- 广泛的测试覆盖
- 通过CocoaPods支持SQLCipher加密
- 可查询的数据库结构和迁移方案
- 在Linux上可用(部分功能受限)
- 社区活跃,提供StackOverflow及Gitter聊天室支持
使用方法
import SQLite
do {
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)
})
let insert = users.insert(name <- "Alice", email <- "alice@mac.com")
let rowid = try db.run(insert)
for user in try db.prepare(users) {
print("id: \(user[id]), name: \(user[name]), email: \(user[email])")
}
let alice = users.filter(id == rowid)
try db.run(alice.update(email <- email.replace("mac.com", with: "me.com")))
try db.run(alice.delete())
try db.scalar(users.count) // 0
} catch {
print(error)
}
SQLite.swift也可以作为轻量级Swift友好的C API包装器使用:
do {
let stmt = try db.prepare("INSERT INTO users (email) VALUES (?)")
for email in ["betty@icloud.com", "cathy@icloud.com"] {
try stmt.run(email)
}
db.totalChanges // 3
db.changes // 1
db.lastInsertRowid // 3
for row in try db.prepare("SELECT id, email FROM users") {
print("id: \(row[0]), email: \(row[1])")
}
try db.scalar("SELECT count(*) FROM users") // 2
} catch {
print(error)
}
探索更多交互式示例,请查看Xcode项目中的Playground。
安装
Swift包管理器
使用Swift包管理器安装:
- 在你的
Package.swift
文件中添加以下代码:
dependencies: [
.package(url: "https://github.com/stephencelis/SQLite.swift.git", from: "0.15.3")
]
- 构建你的项目:
$ swift build
Carthage
通过Carthage安装:
-
确保已安装[Carthage][Carthage Installation]。
-
更新你的Cartfile以包含以下内容:
github "stephencelis/SQLite.swift" ~> 0.15.3
-
运行
carthage update
并按照[指南][Carthage Usage]添加框架。
CocoaPods
通过CocoaPods安装:
-
确保已安装[CocoaPods][CocoaPods Installation]。
-
更新你的Podfile以包含以下内容:
use_frameworks! target 'YourAppTargetName' do pod 'SQLite.swift', '~> 0.14.0' end
-
运行
pod install --repo-update
。
手动安装
- 将SQLite.xcodeproj拖入你的项目。
- 在你的目标的“常规”选项卡中点击"+"按钮,将SQLite.framework添加到“链接库和框架”列表中。
- 对于设备部署,还需在“嵌入式二进制”中添加SQLite.framework。
沟通交流
- 需要帮助或有通用问题?在Stack Overflow提问(标签为
sqlite.swift
)。 - 发现bug或有功能建议?[创建一个问题][]。
- 想要贡献?[提交拉取请求][]。
原始作者
- Stephen Celis (电子邮件)(@stephencelis)
许可证
SQLite.swift遵循MIT许可。更多信息请参见LICENSE文件。
相关项目
增强或使用SQLite.swift的项目:
- SQLiteMigrationManager.swift(受FMDBMigrationManager启发)
替代选择
寻找其他Swift数据库封装库吗?尝试以下选项(或者FMDB):