链式调用
在增删查改一章中,已经介绍了通过 、Table
或 Transaction
操作数据库的方式。它们是经过封装的便捷接口,其实质都是通过调用链式接口完成的。
链式接口都以 prepareXXX
开始,根据不同的调用返回 Insert
、Update
、Delete
、Select
、RowSelect
或 对象。这些对象的基本接口都返回其 self
,因此可以链式连续调用。最后调用对应的函数使其操作生效,如 allObjects
、execute(with:)
等。
通过链式接口,可以更灵活的控制数据库操作。
- let select: Select = try database.prepareSelect(of: Sample.self, fromTable: "sampleTable")
- .where(Sample.Properties.identifier > 1)
- .limit(from: 2, to: 3)
- while let object = try select.nextObject() {
- print(object)
联表查询
在链式类中,Insert
、Update
、Delete
、Select
和 RowSelect
都有其对应的增删查改接口。而 则不同。MultiSelect
用于联表查询,在某些场景下可提供性能,获取更多关联数据等。以下是联表查询的示例代码:
该查询将 "sampleTable" 和 "sampleTableMulti" 表联合起来,取出它们中具有相等 identifier
值的数据。多表查询时,所有同名字段都需要通过 in(table:)
接口指定表名,否则会因为无法确定其属于哪个表从而出错。查询到的 multiObject
是表名到对象的映射,取出后进行类型转换即可。
查询重定向
查询的数据有时候不是字段本身,但仍需将其取出为对象时,可以使用查询重定向。它可以将查询接口重定向到一个指定字段,从而简化操作。
- let object = try database.getObject(on: Sample.Properties.identifier.max().as(Sample.Properties.identifier),
- fromTable: "sampleTable")
- print(object.identifier)
核心层接口
在之前的所有教程中,WCDB Swift 通过其封装的各种接口,简化了最常用的增删查改操作。但 SQL 的操作千变万化,仍会有部分功能无法通过便捷接口满足。此时则可以使用核心层接口。核心层接口通过 CoreStatement
,其本质 SQLite C 接口部分接口的封装,结合可以实现几乎所有 SQL 能够完成的操作。
以下是通过 获取数据的示例代码。
以下是通过 CoreStatement
写入数据的示例代码。
- // 1. 创建 Statement
- let bindingParameters = Array(repeating: Expression.bindingParameter, count: 2)
- let statement = StatementInsert().insert(intoTable: "sampleTable").values(bindingParameters)
- // 2. 创建 CoreStatement
- let coreStatement = try database.prepare(statement)
- for i in 0..<10 {
- // 3. 绑定值
- coreStatement.bind(i, toIndex: 1)
- coreStatement.bind("\(i)", toIndex: 2)
- // 4. 逐步执行 CoreStatement
- try coreStatement.step()
- // 5. 重置绑定
- try coreStatement.reset()
- }
- // try coreStatement.finalize()