Sagar Sharma
Sagar Sharma

Reputation: 118

Basic Slick Insert Example

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.

Upvotes: 9

Views: 10938

Answers (1)

Som Bhattacharyya
Som Bhattacharyya

Reputation: 4112

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.

Upvotes: 19

Related Questions