7

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

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

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

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

对不起,如果愚蠢的问题。

4

3 回答 3

15

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

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

或者,您可以使用以下方法检查是否存在:

select sql from SQLITE_MASTER where name = 'test_table'

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

于 2012-11-06T21:35:59.007 回答
0

每当您CREATE TABLE向 FMDB 发出命令时,它都会在内部将其转换为相应的 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

于 2012-11-06T06:18:53.890 回答
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())")
        }




    }

}
于 2018-05-15T12:50:29.437 回答