0
我對Swift 3和ios相當陌生,以前曾編寫過訪問數據庫的Android程序。 目前的問題是數據庫預填充了10個表,但是,當我嘗試訪問dbase時,無論是在模擬器還是設備中都沒有表,因此無法訪問數據。我搜索了論壇和互聯網,但只能找到信息來檢查數據庫是否存在。 sqlite包裝器是正在使用的FMDB。sqlite嘗試訪問ios時,預填充的數據庫爲空
代碼:
override func viewDidLoad() {
super.viewDidLoad()
let filemgr = FileManager.default
let dirPaths = filemgr.urls(for: .documentDirectory, in: .userDomainMask)
let destPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
databasePath = dirPaths[0].appendingPathComponent("level24.db").path
print(databasePath)
let fullDestPath = URL(fileURLWithPath: destPath).appendingPathComponent("level24.db")
let bundleDatabasePath = Bundle.main.path(forResource: "level24", ofType: ".db")
var level2DB = FMDatabase(path: databasePath as String)
if filemgr.fileExists(atPath: fullDestPath.path){
print("Database file is exist")
print(filemgr.fileExists(atPath: bundleDatabasePath!))
}else{
filemgr.replaceItemAt(databasePath, withItemAt: bundleDatabasePath.path)
}
level2DB = FMDatabase(path: databasePath as String)
if (level2DB?.open())!{
print("Database is open")
var querySQL = "SELECT * FROM sqlite_master WHERE name = '\(tblName)' and type='table'"
let results:FMResultSet? = level2DB?.executeQuery(querySQL, withArgumentsIn:nil)
if (results == nil){
print("Results = \(results)")
do{
try filemgr.copyItem(atPath: bundleDatabasePath!, toPath: fullDestPath.path)
}catch{
print("\n",error)
}
}
print("Results after = \(results)")
let querySQL2 = "SELECT QUESTION FROM tblSani WHERE _ID = 5"
let results2:FMResultSet? = level2DB?.executeQuery(querySQL2, withArgumentsIn:nil)
print(results2?.string(forColumn: "QUESTION") as Any)
}
}
輸出爲:
/Users/***/Library/Developer/CoreSimulator/Devices/4F511422-2F86-49BF-AB10-5CA74B9A7B40/data/Containers/Data/Application/58DD87EB-C20F-4058-B9BC-CCD7ECEEFA98/Documents/level24.db
Database is open
Results after = Optional(<FMResultSet: 0x608000245220>)
2017-04-05 21:09:26.833 Level 2[3161:210849] DB Error: 1 "no such table: tblSani"
2017-04-05 21:09:26.833 Level 2[3161:210849] DB Query: SELECT QUESTION FROM tblSani WHERE _ID = 5
2017-04-05 21:09:26.834 Level 2[3161:210849]DBPath: /Users/***/Library/Developer/CoreSimulator/Devices/4F511422-2F86-49BF-AB10-5CA74B9A7B40/data/Containers/Data/Application/58DD87EB-C20F-4058-B9BC-CCD7ECEEFA98/Documents/level24.db
nil
,如果你能幫助我找到一個解決問題的方法我們將不勝感激。
你檢查了'replaceItemAt'是否被調用,你嘗試從模擬器或應用程序刪除應用程序,然後重新安裝嗎? – luk2302
嗨luk2302已經在模擬器和設備上都嘗試過了,但沒有運氣,當我在數據庫瀏覽器中打開時,仍然沒有dbase中的表 – Badgersoft