如何使用Lifted query和Option列进行简单的光滑插入

时间:2014-05-19 17:48:40

标签: scala insert slick

我似乎无法理解如何使用Slick简单地插入数据库。我在我的Oracle数据库中使用表生成器,我得到了这样的结果:

 case class SimulatonRow(id: scala.math.BigDecimal, startDate: Option[java.sql.Timestamp], endDate: Option[java.sql.Timestamp], numberOfProc: Option[scala.math.BigDecimal], code: String)
  /** GetResult implicit for fetching SimulatonRow objects using plain SQL queries */
  implicit def GetResultSimulatonRow(implicit e0: GR[scala.math.BigDecimal], e1:     GR[Option[java.sql.Timestamp]], e2: GR[Option[scala.math.BigDecimal]], e3: GR[String]): GR[SimulatonRow] = GR{
prs => import prs._
SimulatonRow.tupled((<<[scala.math.BigDecimal], <<?[java.sql.Timestamp], <<?[java.sql.Timestamp], <<?[scala.math.BigDecimal], <<[String]))
  }
 class Simulaton(tag: Tag) extends Table[SimulatonRow](tag, Some("BPRISK"), "SIMULATON") {
def * = (id, startDate, endDate, numberOfProc, code) <> (SimulatonRow.tupled, SimulatonRow.unapply)
/** Maps whole row to an option. Useful for outer joins. */
def ? = (id.?, startDate, endDate, numberOfProc, code.?).shaped.<>({r=>import r._; _1.map(_=> SimulatonRow.tupled((_1.get, _2, _3, _4, _5.get)))}, (_:Any) =>  throw new Exception("Inserting into ? projection not supported."))

/** Database column ID PrimaryKey */
val id: Column[scala.math.BigDecimal] = column[scala.math.BigDecimal]("ID", O.PrimaryKey, O.AutoInc)
/** Database column START_DATE  */
val startDate: Column[Option[java.sql.Timestamp]] = column[Option[java.sql.Timestamp]]("START_DATE")
/** Database column END_DATE  */
val endDate: Column[Option[java.sql.Timestamp]] = column[Option[java.sql.Timestamp]]("END_DATE")
/** Database column NUMBER_OF_PROC  */
val numberOfProc: Column[Option[scala.math.BigDecimal]] = column[Option[scala.math.BigDecimal]]("NUMBER_OF_PROC")
/** Database column CODE  */
val code: Column[String] = column[String]("CODE")
  }

然后我将AutoInc选项添加到主键。

我试过&#39;插入&#39;使用TableQuery [Simulaton] .map或InsertInvoker,但代码无法编译。

它是如何运作的?

我需要制作一个&#39;插入&#39;使用自动增量PK和列 - 代码,startDate。

1 个答案:

答案 0 :(得分:0)

// import driver specific stuff
import MySQLDriver.simple._

// import generated code
import Tables._

// define db connection
val db = Database.for...

// create a connection
db.withSession{ implicit session =>

    // select what should be inserted into
    TableQuery[Simulaton].map(s => (s.code,s.startDate))
                         // insert instead or running the query
                         .insert( ("some code",Some(DateTime.now)) )

}