Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic Slick Insert Example

Tags:

scala

slick

Can anyone please help me with a basic Insert example using Slick 3.1.1. Database used is SQL Server.

For a table named "employee" having columns "employee_id, name, start_date".

This is how I defined the Employee Class:

class Employee(tag: Tag) extends Table[table_types.user](tag,  "EMPLOYEE") {

  def employeeID = column[Int]("EMPLOYEE_ID")
  def empName = column[String]("NAME")
  def startDate = column[String]("START_DATE")

  def * = (employeeID, empName, startDate)
}

And this is what I wrote for creating the table and inserting data:

object Hello extends App {

  val db = Database.forConfig("test")
  val employee = TableQuery[Employee]
  db.run(employee.schema.create)

  try {
    val insert_action = DBIO.seq(employee += (1, "abc", "2016-01-01"))
    db.run(insert_action)
  }
  finally {
    db.close()
  }
}

The table is created fine on the destination database but the row does not get inserted and there are no errors. Any help is much appreciated.

like image 256
Sagar Sharma Avatar asked Apr 06 '16 15:04

Sagar Sharma


1 Answers

I tried this code and it works.

object TestSlick extends App{
  val db = Database.forConfig("h2mem1")
  val employee = TableQuery[Employee]
  try {
  Await.result(db.run(DBIO.seq(
      // create the schema
      employee.schema.create,

      // insert two User instances
      employee += (1, "abc", "2016-01-01"),

      // print the users (select * from USERS)
      employee.result.map(println))), Duration.Inf)
    } finally db.close
}

class Employee(tag: Tag) extends Table[(Int,String,String)](tag,"EMPLOYEE") {
  def employeeID = column[Int]("EMPLOYEE_ID")
  def empName = column[String]("NAME")
  def startDate = column[String]("START_DATE")

  def * = (employeeID, empName, startDate)
}

Basically you need to execute the queries as futures.

like image 155
Som Bhattacharyya Avatar answered Oct 13 '22 00:10

Som Bhattacharyya