使用Swift进行查询并将结果添加到结构中

时间:2018-11-29 18:51:32

标签: swift sqlite

基于Swift的SQLite教程(Link),我能够成功执行以下查询(使用原始查询):

Julie

但是,如果我按如下方式更改查询的样式:

struct myStruct {
   var value1 = String()
   var value2 = String()
   var value3 = String()
   var value4 = String()
}

do {
   guard let queryResults = try? db.prepare("SELECT value1, value2, value3, value4 FROM table WHERE identifier = 0")
   else {
      print("ERROR")
      return
   }
   //first way to get data (works)
   for row in queryResults {
      let data = myStruct(value1: row[0] as! String, value2: row[1] as! String, value3: "", eventDate: row[2] as! String, value4: row[3] as! String)
      tableViewData.append(data)
   }
   //second way to get data into struct     
   _ = queryResults.map { row in
       let data = myStruct(value1: row[0]! as! String, value2: row[1] as! String, value3: "", eventDate: row[2] as! String, value4: row[3] as! String)
       tableViewData.append(data)
   }
}
catch let ex {
   print("ReadDB error: \(ex)")
}

我收到此错误:

  

不能为索引为“ Int”的“ Row”类型下标

有人可以帮我吗?

2 个答案:

答案 0 :(得分:1)

在本教程中,似乎类似

//This is from tutorial

let query = users.select(email)           // SELECT "email" FROM "users"
             .filter(name != nil)     // WHERE "name" IS NOT NULL
             .order(email.desc, name) // ORDER BY "email" DESC, "name"
             .limit(5, offset: 1)     // LIMIT 5 OFFSET 1

.select(item)实际上就是查询本身。因此,只要您这样做

let query = myTable.select(value1, value2, value3, value4).where(identifier == 0),然后这就是查询;您无需为数据库做任何准备。创建此库的人员已尝试使其变得更容易,而您可以执行.select(item)而不是创建语句并将其发送到数据库。

使用上面的示例,您可以看到查询选择了电子邮件,并对其进行了过滤,排序和限制。因此,对于您来说,query是您想要的queryResult-我不确定会返回什么...您将在{{1}上运行query的结果} ... hrm? :P

答案 1 :(得分:0)

这是正确的方法

do {
   let query = myTable.select(value1, value2, value3, value4).where(identifier == 0)
   guard let queryResults = try? db.prepare(query)
   else {
      print("ERROR")
      return
   }
   //option 1
   for row in queryResults {
      let data = myStruct(value1: try row.get(value1), value2: try row.get(value2), value3: try row.get(value3), value4: try row.get(value4))
      tableViewData.append(data)
   }
   //option 2  
   _ = queryResults.map { row in
       let data = myStruct(value1: try row.get(value1), value2: try row.get(value2), value3: try row.get(value3), value4: try row.get(value4))
       tableViewData.append(data)
   }
}
catch let ex {
   print("ReadDB error: \(ex)")
}