SQLite FMDB creating table - beginner iOS
Asked Answered
M

3

7

I think this is a simple question but I didnt find the answer in the FMDB git page. When you use the command:

[database executeUpdate:@"create table T_table(name text primary key, age int)"];

does FMDB or SQLite make some kind of verification to see if the table already exists?

Can I call this method in my class initializer without creating more than one table?

Sorry if stupid question.

Meryl answered 6/11, 2012 at 0:3 Comment(0)
U
0

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

Up answered 6/11, 2012 at 6:18 Comment(0)
H
15

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.

Harmonium answered 6/11, 2012 at 21:35 Comment(0)
U
0

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

Up answered 6/11, 2012 at 6:18 Comment(0)
R
0
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())")
        }




    }

}
Reprobative answered 15/5, 2018 at 12:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.