简体   繁体   English

使用FMDB Swift创建多个表

[英]create multiple table using FMDB Swift

I installed FMDB cocoapods to create database in my app (sqlite) but i stuck in a situation while creating more then one table inside the database. 我在我的应用程序(sqlite)中安装了FMDB cocoapods来创建数据库,但是在数据库中创建多个表时遇到了这种情况。 I created an extension for that. 我为此创建了一个扩展。

Here is my code: 这是我的代码:

extension UIViewController {

    func createTable(table: String){

        let filemgr = NSFileManager.defaultManager()
        let dirPaths = filemgr.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)

        let databasePath = dirPaths[0].URLByAppendingPathComponent("contacts.db").path!

        if !filemgr.fileExistsAtPath(databasePath as String){

            let contactDB = FMDatabase(path: databasePath as String)

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

            if (contactDB?.open())! {
               let sql_stmt = table
               if !(contactDB?.executeStatements(sql_stmt))! {
                    print("Error: \(contactDB?.lastErrorMessage())")
                }else {
                    print("table created")
                }
                contactDB?.close()
            } else {
                print("Error: \(contactDB?.lastErrorMessage())")
            }

        }

    }

}

Calling extension: 附加电话信息:

// calling first time
createTable("CREATE TABLE IF NOT EXISTS CONTACTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT)")

// calling again
reateTable("CREATE TABLE IF NOT EXISTS DESIGNATION (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, DESIG TEXT)")

So when i call extension to create tables it only creates CONTACTS table it doesn't create DESIGNATION table when i call this second time and so on. 因此,当我调用扩展名来创建表时,它仅创建CONTACTS表,而当我第二次调用时则不创建DESIGNATION表,依此类推。

What i am doing wrong here anybody please help inside this. 我在这里做错了任何人,请在其中提供帮助。 Thanks. 谢谢。

Using Swift2. 使用Swift2。

I resolved this by creating a single query statement instead of calling extension again and again to create table. 我通过创建单个查询语句来解决此问题,而不是一次又一次地调用扩展来创建表。

Here is the query: 这是查询:

let tables = "CREATE TABLE IF NOT EXISTS CONTACTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT);" +
             "CREATE TABLE IF NOT EXISTS DESIGNATION (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, DESIG TEXT);"

// calling extension
createTable(tables)

Writing this ans to make useful for other users. 编写此ans使其对其他用户有用。 Thanks everyone :) 感谢大家 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM