本文介绍了有没有办法在 Slick 中进行多次插入/更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 sql 中我们可以这样做:
In sql we can do something like this:
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
有没有办法在 Slick 中进行多次/批量/批量插入或更新?
Is there any way to do multiple/bulk/batch inserts or updates in Slick?
我们可以做类似的事情吗,至少使用 SQL 普通查询?
Can we do something similar, at least using SQL plain queries ?
推荐答案
对于插入,正如 Andrew 回答的那样,您使用 insertALL.
For inserts, as Andrew answered, you use insertALL.
def insertAll(items:Seq[MyCaseClass])(implicit session:Session) = {
(items.size) match {
case s if s > 0 =>
try {
// basequery is the tablequery object
baseQuery.insertAll(tempItems :_*)
} catch {
case e:Exception => e.printStackTrace()
}
Some(tempItems(0))
case _ => None
}
}
对于更新,您是 SOL.查看 Scala slick 2.0 updateAll 相当于 insertALL?我最终做了.解释一下,这是代码:
For updates, you're SOL. Check out Scala slick 2.0 updateAll equivalent to insertALL? for what I ended up doing. To paraphrase, here's the code:
private def batchUpdateQuery = "update table set value = ? where id = ?"
/**
* Dropping to jdbc b/c slick doesnt support this batched update
*/
def batchUpate(batch:List[MyCaseClass])(implicit session:Session) = {
val pstmt = session.conn.prepareStatement(batchUpdateQuery)
batch map { myCaseClass =>
pstmt.setString(1, myCaseClass.value)
pstmt.setString(2, myCaseClass.id)
pstmt.addBatch()
}
session.withTransaction {
pstmt.executeBatch()
}
}
这篇关于有没有办法在 Slick 中进行多次插入/更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!