TinySQLite 0.4.4

TinySQLite 0.4.4

测试已测试
语言语言 SwiftSwift
许可证 MIT
发布最后发布2017年2月
SwiftSwift 版本3.0
SPM支持 SPM

Øyvind Grimnes 维护。



  • 作者
  • Øyvind Grimnes

alt text

使用 Swift 编写的一个轻量级 SQLite 包装器

功能

  • [x] 轻量级
  • [x] 面向对象
  • [x] 自动参数绑定
  • [x] 命名参数绑定
  • [x] 线程安全
  • [x] 支持所有原生 Swift 类型

使用方法

创建数据库对象

将文件 URL 提供给 DatabaseQueue。如果数据库文件已存在,则使用现有的数据库文件。如果不存在,将自动创建新数据库。

let location = URL(fileURLWithPath: "path/to/database.sqlite")

let databaseQueue = DatabaseQueue(location: location)

创建查询

TinySQLite 接受所有有效的 SQLite 查询

要使用自动绑定,请将语句中的值替换为 ‘?’,并提供值的数组

let query = "INSERT INTO YourTable (column, otherColumn) VALUES (?, ?)"

let parameters = [1, "A value"]

要使用自动命名绑定,请将语句中的值替换为 ‘:’,并提供值的字典

let query = "INSERT INTO YourTable (column, otherColumn) VALUES (:column, :otherColumn)"

let parameterMapping = [
    "column": 1, 
    "otherColumn": "A value"
]

执行更新

在数据库中执行更新

try databaseQueue.database { (database) in
    let statement = try database.statement(for: query)

    statement.executeUpdate()
    statement.executeUpdate(withParameters: parameters)
    statement.executeUpdate(withParameterMapping: parameterMapping)

    statement.finalize()
}

执行查询

执行数据库查询。

try databaseQueue.database { (database) in
    let statement = try database.statement(for:query)

    try statement.execute()

    for row in statement {

        /* Get an integer from the second column in the row */
        row.integerForColumn(at: 2)

        /* Get a date from the column called 'deadline' */
        row.dateForColumn("deadline") 

        /* Get a dictionary representing the row */
        row.dictionary 
    }

    statement.finalize()
}

事务

为了提高性能,在执行多个查询时防止更新不完整,可以使用 DatabaseQueuetransaction 方法。如果抛出错误,则会回滚所有更改。

try databaseQueue.transaction { (database) in
    try database.statement(for: query)
                .executeUpdate(withParameters: someParameters)
                .executeUpdate(withParameters: someOtherParameters)
                .executeUpdate(withParameters: evenMoreParameters)
                .finalize()
}

作者

Øyvind Grimnes,[email protected]

许可证

TinySQLite 在 MIT 许可证下可用。查看 LICENSE 文件以获取更多信息。