GRDB.swift是一个SQLite数据库工具包,主要用于应用程序的开发。
与SQLite.swift或FMDB相比,GRDB可以为您提供大量的胶水代码。 与Core Data或Realm相比,它可以简化您的多线程应用程序。
打开数据库连接
import GRDB
// Simple database connection
let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite")
// Enhanced multithreading based on SQLite's WAL mode
let dbPool = try DatabasePool(path: "/path/to/database.sqlite")
执行SQL语句
try dbQueue.inDatabase { db in
try db.execute(
"CREATE TABLE pointOfInterests (" +
"id INTEGER PRIMARY KEY, " +
"title TEXT NOT NULL, " +
"favorite BOOLEAN NOT NULL DEFAULT 0, " +
"latitude DOUBLE NOT NULL, " +
"longitude DOUBLE NOT NULL" +
")")
try db.execute(
"INSERT INTO pointOfInterests (title, favorite, latitude, longitude) " +
"VALUES (?, ?, ?, ?)",
arguments: ["Paris", true, 48.85341, 2.3488])
let parisId = db.lastInsertedRowID
}
获取数据库行和值
try dbQueue.inDatabase { db in
let rows = try Row.fetchCursor(db, "SELECT * FROM pointOfInterests")
while let row = try rows.next() {
let title: String = row.value(named: "title")
let isFavorite: Bool = row.value(named: "favorite")
let coordinate = CLLocationCoordinate2D(
latitude: row.value(named: "latitude"),
longitude: row.value(named: "longitude"))
}
let poiCount = try Int.fetchOne(db, "SELECT COUNT(*) FROM pointOfInterests")! // Int
let poiTitles = try String.fetchAll(db, "SELECT title FROM pointOfInterests") // [String]
}
// Extraction
let poiCount = try dbQueue.inDatabase { db in
try Int.fetchOne(db, "SELECT COUNT(*) FROM pointOfInterests")!
}
添加并提取记录
struct PointOfInterest {
var id: Int64?
var title: String
var isFavorite: Bool
var coordinate: CLLocationCoordinate2D
}
// snip: turn PointOfInterest into a "record" by adopting the protocols that
// provide fetching and persistence methods.
try dbQueue.inDatabase { db in
var berlin = PointOfInterest(
id: nil,
title: "Berlin",
isFavorite: false,
coordinate: CLLocationCoordinate2D(latitude: 52.52437, longitude: 13.41053))
try berlin.insert(db)
berlin.id // some value
berlin.isFavorite = true
try berlin.update(db)
// Fetch [PointOfInterest] from SQL
let pois = try PointOfInterest.fetchAll(db, "SELECT * FROM pointOfInterests")
}
不使用SQL进行查询
try dbQueue.inDatabase { db in
try db.create(table: "pointOfInterests") { t in
t.column("id", .integer).primaryKey()
t.column("title", .text).notNull()
t.column("favorite", .boolean).notNull().defaults(to: false)
t.column("longitude", .double).notNull()
t.column("latitude", .double).notNull()
}
// PointOfInterest?
let paris = try PointOfInterest.fetchOne(db, key: 1)
// PointOfInterest?
let titleColumn = Column("title")
let berlin = try PointOfInterest.filter(titleColumn == "Berlin").fetchOne(db)
// [PointOfInterest]
let favoriteColumn = Column("favorite")
let favoritePois = try PointOfInterest
.filter(favoriteColumn)
.order(titleColumn)
.fetchAll(db)
}