如果该行已经存在,我想更新该行的列,但是如果还不存在,那么我想插入一个新行。
相关问题
通常,这种类型的问题在SQL中很流行
特别是SQLite
寻找SQLite.swift的实现
我试图通过使用SQLite.swift包装器来进行iOS开发来节省开发时间。我选择此框架是因为它是recommended on raywenderlich.com。我认为举一个更新或插入语法的示例将很有用。
战略
在this answer中,Sam Saffron说:
这对我来说很有意义,因此在下面的回答中,我将提供“通常进行更新”的示例。
最佳答案
在此示例中,用户词典存储在自定义键盘上键入的单词。如果单词已经在字典中,则该单词的频率计数将增加1。但是,如果之前未输入该单词,则将插入一个默认频率为1的新行。
该表是使用以下架构创建的:
let userDictionary = Table("user_dictionary")
let wordId = Expression<Int64>("id")
let word = Expression<String>("word")
let frequency = Expression<Int64>("frequency")
// ...
let _ = try db.run( userDictionary.create(ifNotExists: true) {t in
t.column(wordId, primaryKey: true)
t.column(word, unique: true)
t.column(frequency, defaultValue: 1)
})
从问题出发,这就是我们要做的事情:
代码如下所示。
let wordToUpdate = "hello"
// ...
// 1. wrap everything in a transaction
try db.transaction {
// scope the update statement (any row in the word column that equals "hello")
let filteredTable = userDictionary.filter(word == wordToUpdate)
// 2. try to update
if try db.run(filteredTable.update(frequency += 1)) > 0 { // 3. check the rowcount
print("updated word frequency")
} else { // update returned 0 because there was no match
// 4. insert the word
let rowid = try db.run(userDictionary.insert(word <- wordToUpdate))
print("inserted id: \(rowid)")
}
} // 5. if successful, transaction is commited
有关更多帮助,请参见SQLite.swift documentation。
关于ios - 如何使用SQLite.swift更新或插入,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36790444/