EMJ
EMJ

Reputation: 23

SQLite3 generating no such table error in iOS app

My app is generating an error when I attempt to insert values into table.

Here is my code:

import UIKit

class RegisterViewController: UIViewController {

    @IBOutlet weak var firstNameTextField: UITextField!
    @IBOutlet weak var lastNameTextField: UITextField!
    @IBOutlet weak var emailTextField: UITextField!
    @IBOutlet weak var passwordTextField: UITextField!
    @IBOutlet weak var confirmPasswordTextField: UITextField!

    var databasePath = NSString()

    override func viewDidLoad() {
        super.viewDidLoad()
        let filemgr = NSFileManager.defaultManager()
        let dirPaths =
        NSSearchPathForDirectoriesInDomains(.DocumentDirectory,
            .UserDomainMask, true)

        let docsDir = dirPaths[0]

        databasePath = (docsDir as NSString).stringByAppendingPathComponent(
            "users.db")

        if !filemgr.fileExistsAtPath(databasePath as String) {
            let userDB = FMDatabase(path: databasePath as String)

            if userDB == nil {
                print("Error: \(userDB.lastErrorMessage())")
            }

            if userDB.open() {
                let sql_stmt = "CREATE TABLE IF NOT EXISTS USERS (ID INTEGER PRIMARY KEY AUTOINCREMENT, FIRSTNAME VARCHAR(20), LASTNAME VARCHAR(20), EMAIL text, PASSWORD VARCHAR(20))"
                if !userDB.executeStatements(sql_stmt) {
                    print("Error: \(userDB.lastErrorMessage())")
                }
                userDB.close()
            } else {
                print("Error: \(userDB.lastErrorMessage())")
            }
        }

    }

    @IBAction func registerButtonTapped(sender: UIButton) {
        //GetValues
        let userFirstName = firstNameTextField.text
        let userLastName = lastNameTextField.text
        let userEmail = emailTextField.text
        let userPassword = passwordTextField.text
        let userConfirmPassword = confirmPasswordTextField.text

        //check for empty fields
        if(userFirstName!.isEmpty || userLastName!.isEmpty || userEmail!.isEmpty || userPassword!.isEmpty || userConfirmPassword!.isEmpty)
        {
            //Display alert Message
            displayMyAlertMessage("All fields are required")
            return
        }

        //check passwords match
        if (userPassword != userConfirmPassword)
        {
            //display alert message
            displayMyAlertMessage("Passwords do not match")
            return
        }

        //Store Data
        let userDB = FMDatabase(path: databasePath as String)

        if userDB.open() {

            let insertSQL = "INSERT INTO USERS (firstname, lastname, email, password) VALUES ('\(firstNameTextField.text)', '\(lastNameTextField.text)', '\(emailTextField.text)', '\(passwordTextField.text)')"

            let result = userDB.executeUpdate(insertSQL,
                withArgumentsInArray: nil)

            if !result {
                displayMyAlertMessage("Operation failed")
                print("Error: \(userDB.lastErrorMessage())")
                return
            } else {
                displayMyAlertMessage("Thank you for registering \(firstNameTextField.text)")
            }
        }


        //display alert message with confirmation
        let myAlert = UIAlertController(title:"Alert", message:"Registration Successful", preferredStyle: UIAlertControllerStyle.Alert)

        let okAction = UIAlertAction(title:"Ok", style:UIAlertActionStyle.Default) { action in self.dismissViewControllerAnimated(true, completion:nil)
        }
        myAlert.addAction(okAction)
        self.presentViewController(myAlert, animated:true, completion:nil)
    }

    func displayMyAlertMessage(userMessage:String)
    {
        let myAlert = UIAlertController(title:"Alert", message:
            userMessage, preferredStyle:
            UIAlertControllerStyle.Alert);

        let okAction = UIAlertAction(title:"Ok", style:
            UIAlertActionStyle.Default, handler:nil)

        myAlert.addAction(okAction)

        self.presentViewController(myAlert, animated:true,
            completion:nil)

    }
}

Error: no such table: USERS

However, this is created in the viewDidLoad() function. Am I wrong in thinking that the viewDidLoad() function does not need to be called and should have created the users table?

Upvotes: 0

Views: 923

Answers (1)

MD Aslam Ansari
MD Aslam Ansari

Reputation: 1565

You need to check "users.db" file in the document directory of your app.

If its you are using simulator, you will get the path in following line

 let dirPaths =
        NSSearchPathForDirectoriesInDomains(.DocumentDirectory,
            .UserDomainMask, true)
  • Copy the path and Right click on finder.
  • Click on "Go To Folder.." option.
  • Paste the path and click on "Go"

    OR

If you are using device like iPhone then with the help of iFunbox(here) you can access the file.

  • Install the app.
  • Connect the device.
  • Click on the User Applications in left navigation panel.
  • Find your app in right side panel and double click on it.
  • Double click on Documents folder.

If "users.db" file exists, then copy it to desktop and open with sqlitebrowser application(here).

You will be able to see all the tables, columns , data and so on. You can find out, what's wrong and why its not inserting the data.

Note : This is not recommended for other apps. Just for debugging purpose and only your apps.

Upvotes: 1

Related Questions