Sur*_*gch 5 sqlite ios swift sqlite.swift
如果行已经存在,我想更新行的列,但如果它还不存在,那么我想插入一个新行.
这种类型的问题通常适用于SQL
特别是SQLite
我正在尝试通过使用SQLite.swift包装器来开发iOS 来节省开发时间.我选择了这个框架,因为它是在raywenderlich.com上推荐的.我认为有一个更新或插入语法的示例会很有用.
在这个答案中,Sam Saffron说:
如果你一般都在做更新,我会..
- 开始交易
- 做更新
- 检查rowcount
- 如果为0则执行插入操作
- 承诺
如果你通常做插入我会
- 开始交易
- 尝试插入
- 检查主键冲突错误
- 如果我们得到错误,请进行更新
- 承诺
这样你就可以避免选择,并且你在Sqlite上具有事务性.
这对我来说很有意义,所以在下面我的回答中,我提供了一个"通常做更新"的例子.
在此示例中,用户词典存储在自定义键盘上键入的单词。如果该单词已在词典中,则该单词的频率计数会增加 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)
})
Run Code Online (Sandbox Code Playgroud)
从问题来看,这就是我们想要做的:
- 开始交易
- 进行更新
- 检查行数
- 如果是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
Run Code Online (Sandbox Code Playgroud)
请参阅SQLite.swift 文档以获取更多帮助。
| 归档时间: |
|
| 查看次数: |
7257 次 |
| 最近记录: |