更新 db row scala slick [英] Updating db row scala slick

查看:39
本文介绍了更新 db row scala slick的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码将行插入名为 luczekInfo 的表和函数以从数据库中获取数据.我的问题是如何在 get(id) 函数返回的行上创建函数来更新表 luczekInfo 中的列.在 Slick 中更新列值的最佳方法是什么?

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))
  }
}

提前感谢您的回答.

推荐答案

Slick 2.X

您可以通过两种方式更新一行(据我所知),第一种是创建 luczekInfo#TableElementType 类型的行对象并使用它来更新整行:

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
}

我认为你的表有一个名为 name 的文件.

Where I supposed your table has a file called name.

您也可以在 Slick 文档中找到它更新部分.

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

Slick 3.1.X

还有对 insertOrUpdate 的额外支持(upsert) 操作:

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

luczekInfo.insertOrUpdate(row)

这篇关于更新 db row scala slick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆