SQLite FMDB creating table - beginner iOS SQLite FMDB creating table - beginner iOS sqlite sqlite

SQLite FMDB creating table - beginner iOS


Another solution is to change your query to:

create table if not exists test_table (test_no NUMBER, test_name TEXT);

or, you can check for the existence with:

select sql from SQLITE_MASTER where name = 'test_table'

And see if you get any results back.


Whenever you give the CREATE TABLE command to FMDB, it internally converts it into corresponding SQLite query (for which you don't have to worry).

As per the official documentation given on SQLite's website, it states:

"It is usually an error to attempt to create a new table in a database that already contains a table, index or view of the same name."

So, if you try to create another table with the same name, SQLite will throw an error saying:

create table test_table (test_no NUMBER, test_name TEXT); //Table created/* Now, try creating the table again */create table test_table (test_no NUMBER, test_name TEXT); 

You will get the following error.
Error: table test_table already exists

So, SQLite checks for the existence of the table, it won't allow another table with the same name.

Again, you can refer to the documentation to get more details.

Source http://www.sqlite.org/lang_createtable.html


var databasePath = String()    override func viewDidLoad() {        super.viewDidLoad()        let filemgr = FileManager.default        let dirPaths = filemgr.urls(for: .documentDirectory,                                    in: .userDomainMask)        databasePath = dirPaths[0].appendingPathComponent("contacts.db").path        if !filemgr.fileExists(atPath: databasePath as String) {            let contactDB = FMDatabase(path: databasePath as String)            if contactDB == nil {                print("Error: \(contactDB.lastErrorMessage())")            }            if (contactDB.open()) {                let sql_stmt = "CREATE TABLE IF NOT EXISTS CONTACTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT)"                if !(contactDB.executeStatements(sql_stmt)) {                    print("Error: \(contactDB.lastErrorMessage())")                }                contactDB.close()            } else {                print("Error: \(contactDB.lastErrorMessage())")            }        }        save()        // Do any additional setup after loading the view, typically from a nib.    }    override func didReceiveMemoryWarning() {        super.didReceiveMemoryWarning()        // Dispose of any resources that can be recreated.    }    func save()    {        let contactDB = FMDatabase(path: databasePath as String)        if (contactDB.open()) {            let insertSQL = "INSERT INTO CONTACTS (name, address, phone) VALUES ('\("abc")', '\("abc")', '\("1234")')"            let result = contactDB.executeUpdate(insertSQL,                                                  withArgumentsIn: [])            if !result {                //status.text = "Failed to add contact"                print("Error: \(contactDB.lastErrorMessage())")            }            else            {                getData()//                status.text = "Contact Added"//                name.text = ""//                address.text = ""//                phone.text = ""            }        } else {            print("Error: \(contactDB.lastErrorMessage())")        }    }   func getData()    {        let contactDB = FMDatabase(path: databasePath as String)        if (contactDB.open()) {          //  let querySQL = "SELECT address, phone FROM CONTACTS WHERE name = '\(name.text!)'"            let querySQL = "SELECT ID,address, phone FROM CONTACTS"            let results:FMResultSet? = contactDB.executeQuery(querySQL,                                                               withArgumentsIn: [])            while results?.next() == true            {                let id = results?.string(forColumn: "ID")                //(forColumn: "address")                let phone = results?.string(forColumn: "phone")                print(phone ?? "")                print("\(id)")                //status.text = "Record Found"            }//            else//            {//                print("")//               // status.text = "Record not found"//               // address.text = ""////phone.text = ""//            }            contactDB.close()        }        else        {            print("Error: \(contactDB.lastErrorMessage())")        }    }}