【问题标题】:Preloaded SQLite local DB in Swift在 Swift 中预加载 SQLite 本地数据库
【发布时间】:2017-07-05 21:21:15
【问题描述】:

问题

我想在我的项目中使用SQLite.swift 框架来访问位于我当前项目目录中的本地预加载(只读)数据库文件(db.sqlite3)。我将我的数据库连接创建为let db = try? Connection("path/to/db.sqlite3") 第一个问题是当我将数据库保存在我的项目目录中时,我可以将连接路径设置为Connection("path/to/db.sqlite3")Connection("db.sqlite3") 吗? (当然,路径/到的含义是什么,我想知道)无论如何,我的主要问题是如何查询我的本地数据库?怎么了?

这是我的代码,但它不起作用。这段代码大部分类似于 SQLite.swift 的 github documantion page 但它在 Swift 2.2 中不起作用

    override func viewDidLoad() {
    super.viewDidLoad()
    let db = try? Connection("path/to/db.sqlite3")

    let users = Table("users")

    for user in try! db!.prepare(users) {
        print("id: \(user[id]), name: \(user[name]), email: \(user[email])")
        // id: 1, name: Optional("Alice"), email: alice@mac.com
    }

    // Do any additional setup after loading the view.
}

我已经将我的 db 文件复制到 Copy Bundle Resources (Build Phrase)

我的工作目录

错误

注意:我将 db 连接尝试为“path/to/db.sqlite3”和“db.sqlite3”。所以,这不是解决方案。

【问题讨论】:

    标签: ios xcode swift sqlite


    【解决方案1】:

    为 Swift 3+ 更新

    我又仔细阅读了文档,找到了这样的答案:

    let path = Bundle.main.path(forResource: "db", ofType: "sqlite3")!
    
        let db = try? Connection(path, readonly: true)
    
        for row in try! db!.prepare("SELECT id, email FROM users") {
            print("\(row[0]!), \(row[1]!)")
    
        }
    

    【讨论】:

      【解决方案2】:

      Swift 3.0 中转换

      let path = Bundle.main.path(forResource: "SMP", ofType: "sqlite")!
      let db = try? Connection(path)
      

      // 插入行 ======

      let stmt = try! db!.prepare("INSERT INTO tbl_workout (name) VALUES (?)")
      for name in ["Workout1", "Workout2"] {
             try! stmt.run(name)
      }
      

      // 获取行 ======

      for row in try! db!.prepare("SELECT * FROM tbl_workout") {
          print("id: \(String(describing: row[0])), email: \(String(describing: row[1]))")
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-10-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多