在Swift中使用FMDB打开DB

时间:2017-09-07 16:41:01

标签: ios swift sqlite fmdb

我想用FMDB打开现有数据库。数据库应为sqlite数据库,结尾为.db

我的代码是: static let shared:DBManager = DBManager()

let databaseFileName = "/mydb.db"

var pathToDatabase: String!

var pathNSURL: NSURL!

var database: FMDatabase!


override init() {
    super.init()

    let documentsDirectory = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString) as String

    let zwerg = documentsDirectory + databaseFileName

    let pathNSURL = NSURL(fileURLWithPath: zwerg)

    let pathString = documentsDirectory + databaseFileName

    pathToDatabase = pathNSURL.path
    print(pathToDatabase)
}


func firstQuestion() -> Bool {
    if openDatabase(){
        let query = "SELECT * FROM movie"

        do {
            let result = try database.executeQuery(query, values: nil)
            print(result)
        }
        catch {
            print(error.localizedDescription)
        }
        database.close()
        return true
    }
    return false
}

func openDatabase() -> Bool {
    if database == nil {
        print(FileManager.default.fileExists(atPath: pathToDatabase))
        if FileManager.default.fileExists(atPath: pathToDatabase) {
            print("Database set new path -> File exists")
            database = FMDatabase(path: pathToDatabase)
        }
    }

    if database != nil {
        print("Database != nil")
        if database.open() {
            print("Database is open in != nil")
            return true
        }
    }

    return false
}

我从VC调用Method firstQuestion():

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    print(DBManager.shared.firstQuestion())
}

我的问题是fileExists-Method总是返回false。文件名是正确的。这是我的第一个带有swift数据库的项目,所以也许我犯了一个愚蠢的错误......有什么建议吗?

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

let fileManager = FileManager.default
let docURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!

let databaseURL = docURL.appendingPathComponent("databaseNaeme.db")

并将数据库初始化为:

database = FMDatabase(path: databaseURL.absoluteString)