鉴于使用Slick增强了以下Scala类:
val db = Database.forConfig("dbconfig")
try {
val users: TableQuery[Users] = TableQuery[Users]
val action = users.result
val future = db.run(action)
future onComplete {
case Success(u) => u.foreach { user => println("last name : " + **user.lastName**) }
case Failure(t) => println("An error has occured: " + t.getMessage)
}
} finally db.close
我需要在查询循环中打印姓氏:
user.lastName
但是Scala并不认识{{1}}(我得到一个错误说" Scala没有识别符号")。如何打印姓氏?
答案 0 :(得分:1)
问题是你正在使用Table[(Int, String, String)]
。因此,在您的情况下,user
是(Int, String, String)
类型的实例,因此它没有lastName
。使用user._3
获取元组的第三个元素(姓氏)。更好的方法是使用case类而不是元组:
case class DBUser(id: Int, firstName: String, lastName: String)
class Users(tag: Tag) extends Table[DBUser](tag, "users") {
def id: Rep[Int] = column[Int]("sk", O.PrimaryKey)
def firstName: Rep[String] = column[String]("first_name")
def lastName: Rep[String] = column[String]("last_name")
def * = (id, firstName, lastName) <> (DBUser.tupled, DBUser.unapply)
}