4

尝试将 sqlite.swift(swift-2 版本)用于简单的 IOS 应用程序(针对 IOS 9)。我正在使用以下方法创建数据库/连接到现有数据库:

func connectDB() -> Bool {

    let path = NSSearchPathForDirectoriesInDomains(
        .DocumentDirectory, .UserDomainMask, true
        ).first!

    let db = try? Connection("\(path)/db.sqlite3")
    return (db != nil)
}

我可以看到正在磁盘上(在模拟器中)创建的数据库,db.sqlite3,零字节。

现在,当我使用以下方法创建表时:

func createTableVehiclesAndFillFromAPI() -> Bool {
    let vehicles = Table("vehicles")
    let id = Expression<Int64>("id")
    let name = Expression<String?>("name")
    let model = Expression<String>("model")
    let manufacturer = Expression<String>("manufacturer")

    do {
    try db.run(vehicles.create (ifNotExists: true) { t in
        t.column(id, primaryKey: true)
        t.column(name)
        t.column(model)
        t.column(manufacturer)
        })          
    } catch {
       print ("create table vehicles FAILED")
    }

并尝试使用以下方法插入 10 行:

let insert = vehicles.insert(
    name <- item ["name"].stringValue,
    model <- item ["model"].stringValue,
    manufacturer <- item ["manufacturer"].stringValue)

let _ = try! db.run(insert)

最后调用let count = try db.scalar(vehicles.count),输出 10,因此表创建和插入按预期工作。但是,磁盘上 sqlite 数据库的大小不会改变。此外,下次我运行我的应用程序时,将再次重新创建表,就好像数据库再次为空一样。

我在这里遗漏了一些明显的东西吗?

4

0 回答 0