ios - 如何使用 SQLite.swift 更新或插入

标签 ios swift sqlite sqlite.swift

如果该行已经存在,我想更新该行的列,但如果它还不存在,那么我想插入一个新行。

相关问题

这种题型一般是SQL比较流行的

尤其是 SQLite

寻找 SQLite.swift 实现

我试图通过使用 SQLite.swift 来节省开发时间用于 iOS 开发的包装器。我选择这个框架是因为它是 recommended on raywenderlich.com .我认为有一个更新或插入的语法示例会很有用。

策略

this answer , Sam Saffron 说:

If you are generally doing updates I would ..

  1. Begin a transaction
  2. Do the update
  3. Check the rowcount
  4. If it is 0 do the insert
  5. Commit

If you are generally doing inserts I would

  1. Begin a transaction
  2. Try an insert
  3. Check for primary key violation error
  4. if we got an error do the update
  5. Commit

This way you avoid the select and you are transactionally sound on 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)
    })

从问题中得出,这就是我们想要做的:

  1. Begin a transaction
  2. Do the update
  3. Check the rowcount
  4. If it is 0 do the insert
  5. Commit

代码如下所示。

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/

相关文章:

ios - 显示在 iOS 应用程序中打开的 PDF 内容 (Swift)

ios - postNotification 上的 OneSignal 错误

ios - 这是新版本 watchOS 或 iOS 的错误吗?

database - Chrome 将其 SQLite 数据库保存到哪里?

ios - 有没有办法将 CGPoint 的 NSArray<NSValue> 作为 [CGPoint] 公开给 Swift?

ios - 子类化 SKSpriteNode 时物理体问题?

iOS - 自动布局 - View 重叠顶部布局

swift - 获取Core Data实体的所有属性名称; swift

android - 从 Android 应用调试 SQLite 数据库

android - SQLite.insert 返回 -1 但数据已插入数据库