我想这是一个简单的问题,但我在FMDB git页面上没有找到答案。当你使用以下命令时:
[database executeUpdate:@"create table T_table(name text primary key, age int)"];
FMDB或SQLite是否进行某种验证以查看表是否已存在?
我是否可以在我的类初始化程序中调用此方法而不创建多个表?
如果这个问题很愚蠢,那我很抱歉。
另一种解决方案是更改您的查询为:
create table if not exists test_table (test_no NUMBER, test_name TEXT);
或者,您可以使用以下方式检查其是否存在:
select sql from SQLITE_MASTER where name = 'test_table'
看看是否能获得任何结果返回。
CREATE TABLE
命令时,它会将其内部转换为相应的 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);
因此,SQLite会检查表是否存在,它不允许另一个同名的表。
同样,您可以参考文档以获取更多详细信息。
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())")
}
}
}