更新 db row scala slick

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23994003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 06:17:39  来源:igfitidea点击:

Updating db row scala slick

scalaslick

提问by pmalecki

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?

我有以下代码将行插入名为 luczekInfo 的表和函数以从数据库中获取数据。我的问题是如何在 get(id) 函数返回的行上创建函数来更新表 luczekInfo 中的列。在 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.

提前感谢您的回答。

回答by Ende Neu

Slick 2.X

光滑 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:

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

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.

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

You can find it also on the Slick documentationin the section on updating.

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

Slick 3.1.X

光滑 3.1.X

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

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

luczekInfo.insertOrUpdate(row)