使用Swift从bundle打开SQLite

时间:2018-06-12 16:22:00

标签: swift sqlite

我的应用包中有.sqlite文件。我似乎打开了文件,但我无法访问文件中的表格。

let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("test.sqlite")

//opening the database
 if sqlite3_open(fileURL.path, &db) == SQLITE_OK {
   print("opening database")
    }
 let queryString = "SELECT * FROM Table1"

 var stmt:OpaquePointer?

//preparing the query
 if sqlite3_prepare(db, queryString, -1, &stmt, nil) != SQLITE_OK{
       let errmsg = String(cString: sqlite3_errmsg(db)!)
       print("error preparing insert: \(errmsg)")
       return
     }

这会出现以下错误消息:"错误准备插入:没有这样的表:表1"

正如我所看到的,数据库被找到并打开,但无法访问。正如我在Stackoverflow的其他帖子中看到的那样,这应该可行

编辑:我现在看到,如果我将数据库名称从test.sqlite拼错到ttestt.sqlite,我仍然会得到同样的错误。意味着找不到数据库。这条线有什么问题?

 let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("test.sqlite")

1 个答案:

答案 0 :(得分:0)

解决方案是将数据库从bundle复制到documnents目录:

 let bundleURL = Bundle.main.url(forResource: "test", withExtension: "sqlite")!
                try manager.copyItem(at: bundleURL, to: documentsURL)
                rc = sqlite3_open_v2(documentsURL.path, &db, SQLITE_OPEN_READWRITE, nil)