SQLite FMDB创建表 - 初学者iOS

时间:2012-11-06 00:03:06

标签: ios sqlite fmdb

我认为这是一个简单的问题,但我没有在FMDB git页面找到答案。 使用命令时:

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

FMDB或SQLite是否进行某种验证以查看该表是否已存在?

我可以在类初始化程序中调用此方法而不创建多个表吗?

对不起愚蠢的问题。

3 个答案:

答案 0 :(得分:15)

另一种解决方案是将您的查询更改为:

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

或者,您可以通过以下方式检查是否存在:

select sql from SQLITE_MASTER where name = 'test_table'

看看你是否得到了任何结果。

答案 1 :(得分:0)

每当您向FMDB提供CREATE TABLE命令时,它会在内部将其转换为相应的SQLite查询(您不必担心)。

根据SQLite网站上的官方文档,它声明:

"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."

因此,如果您尝试创建另一个具有相同名称的表,SQLite将抛出错误说:

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); 

您将收到以下错误 错误:表test_table已存在

因此,SQLite检查表是否存在,它不允许另一个具有相同名称的表。

同样,您可以参考文档以获取更多详细信息。

来源 http://www.sqlite.org/lang_createtable.html

答案 2 :(得分: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())")
        }




    }

}