Updating db row scala slick

匿名 (未验证) 提交于 2019-12-03 02:24:01

问题:

I have following code which inserts row into table named luczekInfo and function to get data from database. My question is how to make function to update columns from table luczekInfo, on rows returned by get(id) function. What is the best way to update columns values in Slick?

def create(profil: luczekInfo): Either[Failure, luczekInfo] = {   try {     val id = db.withSession {       LuczekInfo returning LuczekInfo.id insert profil     }     Right(profil.copy(id = Some(id)))   } catch {     case e: SQLException =>       Left(databaseError(e))   } }  def get(id: Int): Either[Failure, luczekInfo] = {   try {     db.withSession {       LuczekInfo.findById(id).firstOption match {         case Some(profil: luczekInfo) =>           Right(profil)             case _ =>               Left(notFoundError(id))       }     }   } catch {     case e: SQLException =>       Left(databaseError(e))   } } 

Thanks in advance for answers.

回答1:

Slick 2.X

You can update a row in two ways (as far as I know), the first one would be to create a row object of type luczekInfo#TableElementTypeand use it to update the full row:

def updateById(id: Long, row: luczekInfo#TableElementType)(implicit s: Session): Boolean =   luczekInfo.filter(_.id === id).update(row) 

Or you can update single fields using:

def updateNameById(mId: Long, mName: String)(implicit s: Session) = {   val q = for { l <- luczekInfo if l.id === mId } yield l.name   q.update(mName).run } 

Where I supposed your table has a file called name.

You can find it also on the Slick documentation in the section on updating.

Slick 3.1.X

there's an additional support for the insertOrUpdate (upsert) operation:

luczekInfo.insertOrUpdate(row) 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!