【问题标题】:Convert result set to Seq[(String,String)] using Scala and anorm in play使用 Scala 和 anorm 将结果集转换为 Seq[(String,String)]
【发布时间】:2016-01-25 07:27:38
【问题描述】:

我尝试使用 anorm 从 mySQL 数据库表中获取结果集。这是我的代码。

package models
import play.api.db._
import play.api.Play.current
import scala.collection.mutable._
import anorm._
import anorm.SqlParser._

    case class Brand(id: Int, name: String)


        object Brand {

             /**
            * Parse a Brand from a ResultSet
            */
            val simple = {
                get[Int]("m_brand.idbrand") ~
                get[String]("m_brand.brandName") map {
                case id~name => Brand(id, name)
                }
            }

            /**
            * Construct the Map[String,String] needed to fill a select options set.
            */
            def options: Seq[(String,String)] = DB.withConnection { implicit connection =>
                 SQL("select * from m_brand order by brandName").as(Brand.simple *).
                    foldLeft[Seq[(String, String)]](Nil) { (cs, c) => 
                     c.id.fold(cs) { id => cs :+ (id.toString -> c.name) }
                }
            }

} 

我尝试通过一些实验更改代码但没有成功。

但我得到了这个错误

从标准输出读取: D:\PROJECTS\test\Project_VendorM8\app\models\Brand.scala:69: 类型 不匹配;从标准输出读取:找到: scala.collection.immutable.Nil.type 从标准输出读取:需要: scala.collection.mutable.Seq[(String, String)] D:\PROJECTS\test\Project_VendorM8\app\models\Brand.scala:69: 类型 不匹配;发现:scala.collection.immutable.Nil.type 需要: scala.collection.mutable.Seq[(String, String)] 从标准输出读取: foldLeftSeq[(String, String)] { (cs, c) => foldLeftSeq[(String, String)] { (cs, c) => 从标准输出读取:^

【问题讨论】:

标签: scala playframework anorm


【解决方案1】:

正如 cmets 中所问的那样,更简单的解决方案不仅仅是使用 map 和 write:

def options: Seq[(String,String)] = DB.withConnection { implicit connection =>
  SQL("select * from m_brand order by brandName").as(simple *)
    .map( b => (b.id.toString, b.name))
    .toSeq
}

【讨论】:

    【解决方案2】:

    改变

    foldLeft[Seq[(String, String)]](Nil)
    

    foldLeft(Seq.empty[(String, String)])
    

    【讨论】:

    • 我做了你的改变,但之后我得到了这个错误。 value fold is not a member of Int Read from stdout: c.id.fold(cs) { id => cs :+ (id.toString -> c.name) } c.id.fold(cs) { id => cs :+ (id.toString -> c.name) } Read from stdout: ^
    • 查看id的类型
    • 我看不出.foldLeft 的用途。在结果列表中使用.map 应该没问题。
    猜你喜欢
    • 2016-08-22
    • 1970-01-01
    • 1970-01-01
    • 2018-06-29
    • 2022-08-23
    • 1970-01-01
    • 2014-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多