在此示例中,用户词典存储在自定义键盘上键入的单词。如果该词已在字典中,则该词的频率计数增加 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)
})
从这个问题来看,这就是我们想要做的:
- 开始交易
- 进行更新
- 检查行数
- 如果为 0 则插入
- 犯罪
这是代码的外观。
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 文档。