【问题标题】:How to update or insert with SQLite.swift如何使用 SQLite.swift 更新或插入
【发布时间】:2016-08-15 21:14:32
【问题描述】:

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

相关问题

这种类型的问题通常在 SQL 中很流行

尤其是 SQLite

寻找 SQLite.swift 实现

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

策略

this answer,Sam Saffron 说:

如果您通常进行更新,我会..

  1. 开始交易
  2. 进行更新
  3. 检查行数
  4. 如果为 0 则插入
  5. 提交

如果你通常做插入,我会

  1. 开始交易
  2. 尝试插入
  3. 检查主键违规错误
  4. 如果出现错误,请进行更新
  5. 提交

这样你就可以避免选择并且你在事务上是正确的 Sqlite。

这对我来说很有意义,因此在下面的回答中,我提供了一个“通常进行更新”的示例。

【问题讨论】:

    标签: ios swift sqlite sqlite.swift


    【解决方案1】:

    在此示例中,用户词典存储在自定义键盘上键入的单词。如果该词已经在字典中,则该词的频率计数增加 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. 开始交易
    2. 进行更新
    3. 检查行数
    4. 如果为 0 则插入
    5. 提交

    这是代码的外观。

    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 以获得更多帮助。

    【讨论】:

      【解决方案2】:

      请查看此答案,这是了解如何创建表格并在其中插入行的最佳方式。

      https://stackoverflow.com/a/28642293/5247430

      【讨论】:

        猜你喜欢
        • 2015-12-10
        • 2021-10-20
        • 1970-01-01
        • 2018-10-11
        • 2010-09-24
        • 1970-01-01
        • 2011-05-21
        • 1970-01-01
        • 2012-06-16
        相关资源
        最近更新 更多