Search code examples
swiftfmdb

Update table doesn't work with a real device (fmdb)


I am newbie in iOS development and i have a problem. I am trying to update a table with FMDB but although it has worked in all simulators it doesn't work on a real device. I am sure that the db has been transferred to the device because all the select queries are running properly. On the other hand all the update queries not. I have tried to use NSNumber or NSInteger but ... nothing.

if (database.open())
    {
        let rs = database.executeQuery("update \(TABLE_NAME) set x=1 where id=\(y.getId())",withArgumentsInArray: nil)
        //database.executeUpdate("update \(TABLE_NAME) set x=1 where id=?", withArgumentsInArray:[NSInteger(y.getId())])
        database.close()
    }

Neither of the above solutions works.

Any help?


Solution

  • The problem was that the db file was in the bundle Resources that is read-only. When i copied the db file to the Documents folder everything worked fine.

    I found on http://www.theappguruz.com/blog/use-sqlite-database-swift

    this piece of code

    class func copyFile(fileName: NSString) {
        let dbPath: String = getPath(fileName as String)
        let fileManager = NSFileManager.defaultManager()
        if !fileManager.fileExistsAtPath(dbPath) {
    
            let documentsURL = NSBundle.mainBundle().resourceURL
            let fromPath = documentsURL!.URLByAppendingPathComponent(fileName as String)
    
            var error : NSError?
            do {
                try fileManager.copyItemAtPath(fromPath.path!, toPath: dbPath)
            } catch let error1 as NSError {
                error = error1
            }
            let alert: UIAlertView = UIAlertView()
            if (error != nil) {
                alert.title = "Error Occured"
                alert.message = error?.localizedDescription
            } else {
                alert.title = "Successfully Copy"
                alert.message = "Your database copy successfully"
            }
            alert.delegate = nil
            alert.addButtonWithTitle("Ok")
            alert.show()
        }
    } 
    

    The code with the UIAlertView is an extra, You can omit it.