forked from slick/slick
-
Notifications
You must be signed in to change notification settings - Fork 12
Inserting and Updating
phdoerfler edited this page Oct 5, 2011
·
2 revisions
You can insert a single row into a table with the insert
method or multiple rows with insertAll
:
object Categories extends Table[(Int, String)]("categories") {
def id = column[Int]("id")
def name = column[String]("name")
def * = id ~ name
}
...
Categories insert (1, "Scala")
Categories insertAll (
(2, "ScalaQuery"),
(3, "Windows"),
(4, "Software")
)
These methods are also available on projections. All projection columns must be named columns from a single table (otherwise you will get an exception at runtime; this cannot be enforced statically).
Note that in case of columns with an auto increment option, you must use projections which do not contain those columns:
object Posts extends Table[(Int, String, Int)]("posts") {
def id = column[Int]("id", O AutoInc)
def title = column[String]("title")
def category = column[Int]("category")
def * = id ~ title ~ category
}
...
Posts.title ~ Posts.category insertAll ( // <- 'id' is handled by the DBMS itself (O AutoInc)
("Efficient Parameterized Queries in ScalaQuery", 2),
("A ScalaQuery Update", 2)
)
You can also insert values from a different table or from any kind of query as long as the types match:
class TestTable(name: String) extends Table[(Int, String)](name) {
def id = column[Int]("id")
def name = column[String]("name")
def * = id ~ name
}
object Src1 extends TestTable("src1")
object Dst1 extends TestTable("dst1")
object Dst2 extends TestTable("dst2")
...
Dst1.insert(Src1)
val q2 = for(s <- Src1 if s.id <= 2) yield s
Dst2.insert(q2)
When a query returns a projection of table columns (or a single table column), you can use it to update the rows selected by that query:
val q7 = for(u <- Users if u.first is "Homer") yield u.first
val updated1 = q7.update("Homer Jay")