繁体   English   中英

在播放中使用Scala和anorm将结果集转换为Seq [(String,String)]

[英]Convert result set to Seq[(String,String)] using Scala and anorm in play

我试图使用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)=>从标准输出读取:^

如评论中所问,一个简单的解决方案不仅是使用map并编写:

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
}

更改

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM