2016-04-22 88 views
4

我想更新行的列,如果行已经存在,但如果它不存在,那么我想插入一个新行。如何更新或插入SQLite.swift

相关问题

这种类型的问题是流行的SQL一般

和SQLite特别

寻找SQLite.swift实施

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

战略

this answer,萨姆藏红花说:

如果你通常做更新,我会..

  1. 开始事务
  2. 执行更新
  3. 检查行数
  4. 如果是0做插入
  5. 提交

如果你是一般是在做刀片我会

  1. 开始事务
  2. 尝试插入
  3. 检查主键冲突错误
  4. 如果我们得到一个错误做更新
  5. 提交

这样你可以避免选择和你在 Sqlite上交易声音。

这对我有意义,所以在我的回答下面我提供了一个“通常做更新”的例子。

回答

2

在此示例中,用户词典存储在自定义键盘上键入的单词。如果单词已在词典中,则该单词的频率计数会加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寻求更多帮助。